$(document).ready(function () {
  /*forgot password*/
  $(document).on("click", ".action-get-password", function () {
    var email_or_mobile = $("#forget_email_or_mobile").val();
    if (typeof email_or_mobile == "undefined") {
      email_or_mobile = "";
    }

    var url = "/user/login/get_password";
    $(".action-get-password").html("Vent..");
    $.ajax({
      url: url,
      method: "POST",
      data: {
        email_or_mobile: email_or_mobile,
      },
      dataType: "text",
      success: function (script_response) {
        var data = $.parseJSON(script_response);
        $(".action-get-password").html("Motta kode");

        if (data["success"] == "true") {
          $("#forgot_content").html(data["main_content"]);
        } else if (data["popup_show"] == "true") {
          $("#response_msg").html("");
          $("#commonModal").html(data["main_content"]);
          $("#commonModal").modal();
        } else {
          $("#response_msg").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );
        }
      },
    });
  });

  $(document).on("click", ".action-password-step-2", function () {
    var email_or_mobile = $("#forget_email_or_mobile").val();
    if (typeof email_or_mobile == "undefined") {
      email_or_mobile = "";
    }
    var forget_code = $("#forget_code").val();
    var contentType = $("#contentType").val();

    var url = "/user/login/get_password_step_2";
    $(".action-password-step-2").html("Vent..");

    $.ajax({
      url: url,
      method: "POST",
      data: {
        email_or_mobile: email_or_mobile,
        forget_code: forget_code,
        contentType: contentType,
      },
      dataType: "text",
      success: function (script_response) {
        var data = $.parseJSON(script_response);
        $(".action-password-step-2").html("Videre");

        if (data["success"] == "true") {
          if (contentType == "sidebarPopup") {
            $("#sidebar-response").html(data["main_content"]);
          } else {
            $("#forgot_content").html(data["main_content"]);
          }
        } else {
          $("#response_msg").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );
        }
      },
    });
  });

  $(document).on("click", ".action-password-step-3", function () {
    var jobFrm = $("#form-pass").serializeArray();
    let createpassword1 = $("#createpassword-1").val();

    var url = "/user/login/change_password_step_3";
    if ($(this).html() == "Ferdig") {
      $("#password-change").modal("hide");
      return false;
    }
    $(".action-password-step-3").html("Vent..");

    $.ajax({
      url: url,
      method: "POST",
      data: {
        jobFrm: jobFrm,
        createpassword1: createpassword1,
      },
      dataType: "text",
      success: function (script_response) {
        $(".action-password-step-3").html("Logg inn");
        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          window.location.href = "/profile";
        } else {
          $("#response_msg").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );
        }
      },
    });
  });

  /*forgot password*/

  /*forgot password*/
  $(document).on("click", ".action-get-password-m", function () {
    var email_or_mobile = $("#forget_email_or_mobile").val();
    if (typeof email_or_mobile == "undefined") {
      email_or_mobile = "";
    }
    var contentType = "sidebarPopup";

    var url = "/user/login/get_password";
    $(".action-get-password-m").html("Vent..");
    $.ajax({
      url: url,
      method: "POST",
      data: {
        email_or_mobile: email_or_mobile,
        contentType: contentType,
      },
      dataType: "text",
      success: function (script_response) {
        var data = $.parseJSON(script_response);
        $(".action-get-password-m").html("Send kode");

        if (data["success"] == "true") {
          $("#sidebar-response").html(data["main_content"]);
        } else if (data["popup_show"] == "true") {
          $("#response_msg").html("");
          $("#commonModal").html(data["main_content"]);
          $("#commonModal").modal();
        } else {
          $("#response_msg").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );
        }

        /*
        if (data["success"] == "true" && data["redirect"] == "true") {
          $("#response_msg").html("");

          $("#sidebar-response").html(data["main_mobile_content"]);
        } else if (data["success"] == "true" && data["redirect"] == "false") {
          $("#response_msg").html("");
          $("#commonModal").html(data["main_content"]);
          $("#commonModal").modal();
        } else {
          $("#response_msg").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>"
          );
        }
		*/

        setTimeout(function () {
          $("#response_msg").html("");
        }, 6000);
      },
    });
  });
  /*forgot password*/

  /*action-btn-login-popup*/
  $(document).on("click", ".action-btn-login-popup", function () {
    var email_or_mobile = $("#loginFrm #email_or_mobile").val();
    if (typeof email_or_mobile == "undefined" || email_or_mobile == "") {
      var email_or_mobile = $("#loginFrmPopup #email_or_mobile").val();
    }
    if (typeof email_or_mobile == "undefined") {
      var email_or_mobile = "";
    }

    var password = $("#loginFrm  #password").val();
    if (typeof password == "undefined" || password == "") {
      var password = $("#loginFrmPopup  #password").val();
    }
    if (typeof password == "undefined") {
      var password = "";
    }

    var remember = $("#loginFrm  #remember:checked").val();
    if (typeof remember == "undefined" || remember == "") {
      var remember = $("#loginFrmPopup  #remember:checked").val();
    }
    if (typeof remember == "undefined") {
      var remember = "";
    }

    let remember_popup = 0;
    let remember_choice = 0;

    var url = "/user/login/check_user_login_message";
    $(".action-btn-login-popup").html("Vent..");

    $.ajax({
      url: url,
      method: "POST",
      data: {
        email_or_mobile: email_or_mobile,
        password: password,
        remember: remember,
        remember_popup: remember_popup,
        remember_choice: remember_choice,
      },
      dataType: "text",
      success: function (script_response) {
        var data = $.parseJSON(script_response);
        $(".action-btn-login-popup").html(
          'Logg inn <i class="fas fa-chevron-right" style="font-weight: bolder" aria-hidden="true"></i>',
        );

        if (data["success"] == "true") {
          if (
            data["redirect"] != "" &&
            typeof data["redirect"] != "undefined"
          ) {
            window.location.href = data["redirect"];
          } else if (typeof job_id == "undefined") {
            window.location.href = "/profile";
          } else {
            var job_id = $("#job_id").val();
            var chat_id = $("#chat_id").val();

            var append_data = "";
            if (job_id != "") {
              append_data = "?job_id=" + job_id + "&chat_id=" + chat_id + "";
            }
            window.location.href = "/messages" + append_data + "";
          }
        } else if (data["success"] == "remember_popup") {
          $("#commonModal").html(data["main_content"]);
          $("#commonModal").modal();
          $("#commonModal").css("z-index", 999999);
        } else {
          $(".LoginResponse").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );

          setTimeout(function () {
            $(".LoginResponse").html("");
          }, 6000);
        }
      },
    });
  });

  /*action-btn-login-popup*/

  /*action-remember*/
  $(document).on(
    "click",
    ".action-remember-yes,.action-remember-no",
    function () {
      console.log("action-remember");

      var remember_choice = $(this).hasClass("action-remember-yes") ? 1 : 0;

      var email_or_mobile = $("#loginFrm #email_or_mobile").val();
      if (typeof email_or_mobile == "undefined" || email_or_mobile == "") {
        var email_or_mobile = $("#loginFrmPopup #email_or_mobile").val();
      }
      if (typeof email_or_mobile == "undefined") {
        var email_or_mobile = "";
      }

      var password = $("#loginFrm  #password").val();
      if (typeof password == "undefined" || password == "") {
        var password = $("#loginFrmPopup  #password").val();
      }
      if (typeof password == "undefined") {
        var password = "";
      }

      var remember = $("#loginFrm  #remember:checked").val();
      if (typeof remember == "undefined" || remember == "") {
        var remember = $("#loginFrmPopup  #remember:checked").val();
      }
      if (typeof remember == "undefined") {
        var remember = "";
      }

      var url = "/user/login/check_user_login_message";

      var this_text = $(this).html();

      $(this).html("Vent..");

      $.ajax({
        url: url,
        method: "POST",
        data: {
          email_or_mobile: email_or_mobile,
          password: password,
          remember: remember,
          remember_choice: remember_choice,
          remember_popup: "1",
        },
        dataType: "text",
        success: function (script_response) {
          var data = $.parseJSON(script_response);

          $(this).html(this_text);

          if (data["success"] == "true") {
            if (
              data["redirect"] != "" &&
              typeof data["redirect"] != "undefined"
            ) {
              window.location.href = data["redirect"];
            } else if (typeof job_id == "undefined") {
              window.location.href = "/profile";
            } else {
              var job_id = $("#job_id").val();
              var chat_id = $("#chat_id").val();

              var append_data = "";
              if (job_id != "") {
                append_data = "?job_id=" + job_id + "&chat_id=" + chat_id + "";
              }
              window.location.href = "/messages" + append_data + "";
            }
          } else {
            $(".LoginResponse").html(
              "<div class='response-msg alert alert-danger'>" +
                data["message"] +
                "</div>",
            );

            setTimeout(function () {
              $(".LoginResponse").html("");
            }, 6000);
          }
        },
      });
    },
  );
  /*action-remember*/

  $(document).on("click", ".job-btn-next-2", function () {
    $("#job_msg").html("");

    $(".job-btn-next-2").html("Vent..");
    var jobFrm = $("#jobFrm").serializeArray();
    var imagess = [];
    $("#jobFrm input[name='image[]']").each(function () {
      var vals = $(this).val();
      imagess.push(vals);
    });
    /* console.log(JSON.stringify(imagess)); */
    var url = "/newjob/step2";
    $.ajax({
      url: url,
      method: "POST",
      data: {
        jobFrm: jobFrm,
        image: imagess,
      },
      dataType: "text",
      success: function (script_response) {
        $(".job-btn-next-2").html("Neste");
        setTimeout(function () {
          /* console.log("yes"); */
          /* 
					$("#tr_from_address").val("");
                    $("#tr_from_address_administrative_area_level_1").val("");
                    $("#tr_to_address").val("");
                    $("#tr_to_address_administrative_area_level_1").val(""); 
					*/
        }, 600);

        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          $("#job_msg").html("");
          $(".job-content").html(data["main_content"]);

          /* setTimeout(function () {
                        initMap4(); 
                        initMap5();
                    }, 1000); */

          $(document).one("keyup", ".geo-address", function () {
            console.log("Step = keyup");
            $("#googleidsearch").val(this.id);
            initMap4();
          });

          $(document).one("keyup", ".map-offshore-address-norway", function () {
            $("#googleidsearch").val(this.id);
            globalinitMap_norway();
          });
          $(document).one(
            "keyup",
            ".map-offshore-address-norway2",
            function () {
              $("#googleidsearch").val(this.id);
              globalinitMap_norway();
            },
          );
          $(document).one("keyup", ".map-offshore-address-global", function () {
            $("#googleidsearch").val(this.id);
            globalinitMap_global();
          });
          $(document).one(
            "keyup",
            ".map-offshore-address-global2",
            function () {
              $("#googleidsearch").val(this.id);
              globalinitMap_global();
            },
          );

          /* setTimeout(function () { 
						if($("#tr_to_address").val()!=""){
							console.log("tr find");
							$("#tr_to_address").trigger('change');
						}else if($("#where_address").val()!=""){
							console.log("where find");
							$("#where_address").trigger('change'); 
						} 
                    }, 1100); 
					*/

          setTimeout(function () {
            if ($("#where_address").length > 0) {
              initMap2();
            } else {
              initMap();
            }
          }, 800);

          console.log(data["DeviceType"]);

          if (data["DeviceType"] == "mobile") {
            setTimeout(function () {
              $("html, body").animate(
                { scrollTop: localStorage.getItem("mobile-job-quote-scroll") },
                100,
              );
            }, 500);
          }
        } else {
          $("#job_msg").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );
        }
      },
    });
  });
  $(document).on("click", ".job-btn-back-1", function () {
    $("#job_msg").html("");

    var jobFrm = $("#jobFrm").serializeArray();
    var imagess = [];
    $("#jobFrm input[name='image[]']").each(function () {
      var vals = $(this).val();
      imagess.push(vals);
    });
    var url = "/newjob/backstep1";
    $.ajax({
      url: url,
      method: "POST",
      data: {
        jobFrm: jobFrm,
        image: imagess,
      },
      dataType: "text",
      success: function (script_response) {
        /* console.log(script_response); */
        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          $("#job_msg").html("");
          $(".job-content").html(data["main_content"]);

          console.log(data["DeviceType"]);
          if (data["DeviceType"] == "mobile") {
            setTimeout(function () {
              $("html, body").animate(
                { scrollTop: localStorage.getItem("mobile-job-quote-scroll") },
                100,
              );
            }, 500);
          }
        } else {
          $("#job_msg").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );
        }
      },
    });
  });
  $(document).on("click", ".job-btn-next-3", function () {
    $("#job_msg").html("");

    $(".job-btn-next-3").html("Vent..");
    var jobFrm = $("#jobFrm").serializeArray();
    var imagess = [];
    $("#jobFrm input[name='image[]']").each(function () {
      var vals = $(this).val();
      imagess.push(vals);
    });
    var url = "/newjob/step3";
    $.ajax({
      url: url,
      method: "POST",
      data: {
        jobFrm: jobFrm,
        image: imagess,
      },
      dataType: "text",
      success: function (script_response) {
        $(".job-btn-next-3").html("Neste");
        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          $("#job_msg").html("");
          $(".job-content").html(data["main_content"]);
          setTimeout(function () {
            event_price_change();
          }, 600);
          console.log(data["DeviceType"]);
          if (data["DeviceType"] == "mobile") {
            setTimeout(function () {
              $("html, body").animate(
                { scrollTop: localStorage.getItem("mobile-job-quote-scroll") },
                100,
              );
            }, 500);
          }
        } else {
          $(document).one("keyup", ".map-offshore-address-norway", function () {
            $("#googleidsearch").val(this.id);
            globalinitMap_norway();
          });
          $(document).one(
            "keyup",
            ".map-offshore-address-norway2",
            function () {
              $("#googleidsearch").val(this.id);
              globalinitMap_norway();
            },
          );
          $(document).one("keyup", ".map-offshore-address-global", function () {
            $("#googleidsearch").val(this.id);
            globalinitMap_global();
          });
          $(document).one(
            "keyup",
            ".map-offshore-address-global2",
            function () {
              $("#googleidsearch").val(this.id);
              globalinitMap_global();
            },
          );
          /* 
					if (data['tr_to_zipcode'] == '1') {
                        $("input[name='tr_to_zipcode']").attr("type", "text");
                        $("#tr_to_zipcode_label").show();
                    }
                    if (data['tr_from_zipcode'] == '1') {
                        $("input[name='tr_from_zipcode']").attr("type", "text");
                        $("#tr_from_zipcode_label").show();
                    }
					if (data['where_zipcode'] == '1') {
                        $("input[name='where_zipcode']").attr("type", "text");
                        $("#where_zipcode_label").show();
                    } 
					*/
          console.log("tr_to_zipcode status=" + data["tr_to_zipcode"]);
          if (data["tr_to_zipcode"] == "1") {
            $("input[name='tr_to_address']").val("");
          }

          console.log("tr_from_zipcode status=" + data["tr_from_zipcode"]);
          if (data["tr_from_zipcode"] == "1") {
            $("input[name='tr_from_address']").val("");
          }

          console.log("where_address status=" + data["where_address"]);
          if (data["where_zipcode"] == "1") {
            $("input[name='where_address']").val("");
          }

          $("#job_msg").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );
        }
      },
    });
  });
  $(document).on("click", ".job-btn-back-2", function () {
    $("#job_msg").html("");
    var jobFrm = $("#jobFrm").serializeArray();
    var imagess = [];
    $("#jobFrm input[name='image[]']").each(function () {
      var vals = $(this).val();
      imagess.push(vals);
    });
    var url = "/newjob/backstep2";
    $.ajax({
      url: url,
      method: "POST",
      data: {
        jobFrm: jobFrm,
        image: imagess,
      },
      dataType: "text",
      success: function (script_response) {
        /* console.log(script_response); */
        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          $("#job_msg").html("");
          $(".job-content").html(data["main_content"]);

          /* setTimeout(function () {
                        initMap4();
                        initMap5();
                    }, 600); */

          $(document).one("keyup", ".geo-address", function () {
            console.log("Step = keyup");
            $("#googleidsearch").val(this.id);
            initMap4();
          });

          $(document).one("keyup", ".map-offshore-address-norway", function () {
            $("#googleidsearch").val(this.id);
            globalinitMap_norway();
          });
          $(document).one(
            "keyup",
            ".map-offshore-address-norway2",
            function () {
              $("#googleidsearch").val(this.id);
              globalinitMap_norway();
            },
          );
          $(document).one("keyup", ".map-offshore-address-global", function () {
            $("#googleidsearch").val(this.id);
            globalinitMap_global();
          });
          $(document).one(
            "keyup",
            ".map-offshore-address-global2",
            function () {
              $("#googleidsearch").val(this.id);
              globalinitMap_global();
            },
          );

          /* setTimeout(function () {
						
						if($("#tr_to_address").val()!=""){
							console.log("tr find");
							$("#tr_to_address").trigger('change');
						}else if($("#where_address").val()!=""){
							console.log("where find");
							$("#where_address").trigger('change'); 
						}
						
                    }, 1100); */

          setTimeout(function () {
            if ($("#where_address").length > 0) {
              initMap2();
            } else {
              initMap();
            }
          }, 800);

          console.log(data["DeviceType"]);
          if (data["DeviceType"] == "mobile") {
            setTimeout(function () {
              $("html, body").animate(
                { scrollTop: localStorage.getItem("mobile-job-quote-scroll") },
                100,
              );
            }, 500);
          }
        } else {
          $("#job_msg").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );
        }
      },
    });
  });

  $(document).on("change", "#any_location_status", function () {
    console.log("any_location_status changed");

    if ($("#any_location_status").is(":checked")) {
      $("#fromHelp").html("Skriv inn en adresse der jobben skal utføres.");

      $("#where_address").attr("type", "text");
      $("label[for='where_address']").show();

      $("#where_address_street").attr("type", "text");
    } else {
      $("#fromHelp").html(
        "Oppdraget krever ikke fysisk oppmøte og kan utføres fra hele Norge.",
      );

      $("#where_address").attr("type", "hidden");
      $("label[for='where_address']").hide();

      $("#where_address_street").attr("type", "hidden");
      $("#where_address_street").hide();

      if ($("#where_address").val() == "") {
        /* $("#where_address").val("Norway"); */
      }
    }

    $("#where_address").trigger("change");
  });

  $(document).on("change", "input[name='jobsubtype_id']", function () {
    var jobsubtype_id = $(this).val();
    var url = "/newjob/check_any_location_status";

    $.ajax({
      url: url,
      method: "POST",
      data: {
        jobsubtype_id: jobsubtype_id,
      },
      dataType: "text",
      success: function (script_response) {
        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          $(".col-any-location-status").html(data["main_content"]);

          $("#where_address").attr("type", "text");
          $("label[for='where_address']").show();

          $("#fromHelp").html("Skriv inn en adresse der jobben skal utføres.");

          /* if($("#where_address").val()=="Norway"){
						 $("#where_address").val("");
					 } */
        }
      },
    });
  });

  $(document).on("click", ".action-translate-en", function () {
    $("#job_msg").html("");

    var frmtype = $("body").attr("frmtype");
    var self_service_form = "";
    var self_service_form = $("#self_service_form").serializeArray();
    var jobFrm = $("#jobFrm").serializeArray();
    var imagess = [];
    $("#jobFrm input[name='image[]']").each(function () {
      var vals = $(this).val();
      imagess.push(vals);
    });
    var url = "/newjob/self_approve_check_en";

    $.ajax({
      url: url,
      method: "POST",
      data: {
        jobFrm: jobFrm,
        self_service_form: self_service_form,
        image: imagess,
        frmtype: frmtype,
      },
      dataType: "text",
      success: function (script_response) {
        $(".job-btn-publish-check").html("Legg ut");
        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          /*$("#publish-job").addClass("publish-job-modal");*/
          $("#job_msg").html("");
          $("#publish-job").html(data["main_content"]);
        } else {
          $("#job_msg").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );
        }
      },
    });
  });

  $(document).on("click", ".action-translate-norway", function () {
    $("#job_msg").html("");

    var frmtype = $("body").attr("frmtype");
    var self_service_form = "";
    var self_service_form = $("#self_service_form").serializeArray();
    var jobFrm = $("#jobFrm").serializeArray();
    var imagess = [];
    $("#jobFrm input[name='image[]']").each(function () {
      var vals = $(this).val();
      imagess.push(vals);
    });
    var url = "/newjob/self_approve_check";

    $.ajax({
      url: url,
      method: "POST",
      data: {
        jobFrm: jobFrm,
        self_service_form: self_service_form,
        image: imagess,
        frmtype: frmtype,
      },
      dataType: "text",
      success: function (script_response) {
        $(".job-btn-publish-check").html("Legg ut");
        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          /* $("#publish-job").addClass("publish-job-modal");*/
          $("#job_msg").html("");
          $("#publish-job").html(data["main_content"]);
        } else {
          if (data["option_professional"] == true) {
            $("#inspectionButton")
              .html(`<button class="btn custom-select error" data-toggle="modal" data-target="#inspectionModalCenter">
									<div class="head-title d-flex mb-2">
										<div class="label d-flex g-5"><i class="fa-regular fa-circle-exclamation"></i><h6>Velg type oppdrag</h6><span class="danger">Du må velge type oppdrag</span></div>
										<i class="fa-solid fa-chevron-right ml-auto"></i>
									</div>
								</button>`);
          }

          if (data["message"] != "") {
            $("#job_msg").html(
              "<div class='response-msg alert alert-danger'>" +
                data["message"] +
                "</div>",
            );
          }
        }

        setTimeout(function () {
          $("#job_msg").html("");
        }, 6000);
      },
    });
  });

  /*job-btn-publish*/
  $(document).on("click", ".job-btn-publish-check", function () {
    var self_service_form = "";
    var self_service_form = $("#self_service_form").serializeArray();
    var jobFrm = $("#jobFrm").serializeArray();
    var imagess = [];
    $("#jobFrm input[name='image[]']").each(function () {
      var vals = $(this).val();
      imagess.push(vals);
    });
    var url = "/newjob/self_approve_check";
    $(".job-btn-publish-check").html("Vent..");

    $("body").attr("frmtype", "publish");

    $.ajax({
      url: url,
      method: "POST",
      data: {
        jobFrm: jobFrm,
        self_service_form: self_service_form,
        image: imagess,
        frmtype: "publish",
      },
      dataType: "text",
      success: function (script_response) {
        $(".job-btn-publish-check").html("Legg ut");
        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          /*$("#publish-job").addClass("publish-job-modal");*/
          $("#job_msg").html("");
          $("#publish-job").html(data["main_content"]);
          $("#publish-job").modal();
        } else {
          if (data["option_professional"] == true) {
            $("#inspectionButton")
              .html(`<button class="btn custom-select error" data-toggle="modal" data-target="#inspectionModalCenter">
									<div class="head-title d-flex mb-2">
										<div class="label d-flex g-5"><i class="fa-regular fa-circle-exclamation"></i><h6>Velg type oppdrag</h6><span class="danger">Du må velge type oppdrag</span></div>
										<i class="fa-solid fa-chevron-right ml-auto"></i>
									</div>
								</button>`);
          }

          if (data["message"] != "") {
            $("#job_msg").html(
              "<div class='response-msg alert alert-danger'>" +
                data["message"] +
                "</div>",
            );
          }
        }
      },
    });
  });

  $(document).on("click", ".job-btn-publish", function () {
    var self_service_form = "";
    var self_service_form = $("#self_service_form").serializeArray();
    var jobFrm = $("#jobFrm").serializeArray();
    var imagess = [];
    $("#jobFrm input[name='image[]']").each(function () {
      var vals = $(this).val();
      imagess.push(vals);
    });
    var payment_type = $("input:radio[name='payment_type']:checked").val();

    var url = "/newjob/publish";
    $(".job-btn-publish").html("Vent..");
    $(".job-btn-publish").attr("disabled", "disabled");
    $(".job-btn-publish").prop("disabled", true);

    $.ajax({
      url: url,
      method: "POST",
      data: {
        jobFrm: jobFrm,
        self_service_form: self_service_form,
        image: imagess,
      },
      dataType: "text",
      success: function (script_response) {
        $("#action-job-manalApproval").html(
          '<i class="fas fa-eye" aria-hidden="true"></i> Manal approval',
        );
        $("#action-job-selfApproval").html(
          '<i class="fak fa-yencheck" aria-hidden="true"></i> Self Approve',
        );

        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          gtag_report_conversion();

          console.log(data["redirect_true"]);

          if (typeof data["redirect_true"] != "undefined") {
            window.location.href = "/login";
          } else {
            /*$("#publish-job").removeClass("publish-job-modal");*/
            $("#publish-job").html(data["main_content"]);

            $(".justify-content-end").remove();
            $(".job-btn-publish").remove();

            $("#publish-job").modal({
              backdrop: "static",
              keyboard: false,
            });
          }
        } else {
          $("#publish-job").modal("hide");
          $("#job_msg").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );
        }
      },
    });
  });

  $(document).on("change", "#self_service_form input", function () {
    var self_approve_1 = $(
      "input:checkbox[name='self_approve_1']:checked",
    ).val();
    var self_approve_2 = $(
      "input:checkbox[name='self_approve_2']:checked",
    ).val();
    var self_approve_3 = $(
      "input:checkbox[name='self_approve_3']:checked",
    ).val();
    var self_approve_4 = $(
      "input:checkbox[name='self_approve_4']:checked",
    ).val();

    if (
      self_approve_1 == "1" &&
      self_approve_2 == "1" &&
      self_approve_3 == "1" &&
      self_approve_4 == "1"
    ) {
      $("#action-job-manalApproval").hide();
      $("#action-job-selfApproval").show();
    } else {
      $("#action-job-manalApproval").show();
      $("#action-job-selfApproval").hide();
    }
  });

  /*job-btn-publish*/

  $(document).on("click", ".trigger-image", function () {
    $("#image_upload_101").trigger("click");
  });
  $(document).on("change", ".job_image_upload11", function () {
    var this_id = $(this).attr("id");
    var image_name = $(this).attr("image-name");
    var file_data = $("#" + this_id + "").prop("files")[0];
    var form_data = new FormData();
    form_data.append("file", file_data);
    form_data.append("type", "image");
    $("#img_job_error").html('<p class="error">Vent litt. Laster opp..</p>');
    $(".job-btn-next-2").hide();
    $(".job-img:last").hide();
    $("#loadingImage").modal("show");
    $.ajax({
      url: "/ajax/job_image_uploads",
      cache: false,
      contentType: false,
      processData: false,
      data: form_data,
      type: "post",
      success: function (php_script_response) {
        var data = jQuery.parseJSON(php_script_response);
        if (php_script_response != "") {
          $(".job_image_upload").val("");
          if (data["success"] == "true") {
            var html = data["list"];
            setTimeout(function () {
              $("#loadingImage").modal("hide");
              $(".job-img:last").before(html);
              $("#img_job_error").html("");
              $(".job-btn-next-2").show();
              $(".job-img:last").show();
            }, 2000);
          } else {
            $("#img_job_error").html(data["msg"]);
          }
        }
      },
    });
  });
  $(document).on("change", ".job_image_upload", function () {
    $("#loadingImage").modal("show");
    $("#loadingImage .progress-bar").css("width", "0");
    var this_id = $(this).attr("id");
    var image_name = $(this).attr("image-name");
    var file_data = $("#" + this_id + "").prop("files")[0];
    var file_data = $("#" + this_id + "").prop("files")[0];
    var form_data = new FormData();
    form_data.append("file", file_data);
    form_data.append("type", "image");
    $.ajax({
      url: "/ajax/job_image_uploads",
      data: form_data,
      processData: false,
      contentType: false,
      type: "POST",
      xhr: function () {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener(
          "progress",
          function (evt) {
            if (evt.lengthComputable) {
              var percentComplete = evt.loaded / evt.total;
              percentComplete = parseInt(percentComplete * 100);
              $("#loadingImage .progress-bar").text(percentComplete + "%");
              $("#loadingImage .progress-bar").css(
                "width",
                percentComplete + "%",
              );
            }
          },
          false,
        );
        return xhr;
      },
      success: function (php_script_response) {
        var data = jQuery.parseJSON(php_script_response);
        if (php_script_response != "") {
          $(".job_image_upload").val("");
          if (data["success"] == "true") {
            var html = data["list"];
            setTimeout(function () {
              $("#loadingImage").modal("hide");
              $("#loadingImage .progress-bar").css("width", "0");
              $(".job-img:last").before(html);
              $("#img_job_error").html("");
              $(".job-btn-next-2").show();
              $(".job-img:last").show();
            }, 2000);
          } else {
            $("#img_job_error").html(data["msg"]);
            setTimeout(function () {
              $("#loadingImage").modal("hide");
              $("#loadingImage .progress-bar").css("width", "0");
            }, 2000);
          }
        }
      },
    });
  });

  $(document).on("click", ".action-addpicture", function () {
    $("#image_upload_101").trigger("click");
  });

  $(document).on("click", ".action-takepicture-2", function () {
    $("#image_upload_102").trigger("click");
    $("#cancelProfileImg").trigger("click");
  });

  /* $(document).on("click", '.addpicture', function () {
        $("#image_upload_101").trigger('click');
    }); */

  $(document).on("click", ".action-remove-profile-image", function () {
    var url = "/user/profile/remove_profile_image";
    $.ajax({
      url: url,
      method: "POST",
      data: {
        type: "",
      },
      dataType: "text",
      success: function (script_response) {
        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          $("#picture-holder").attr("style", "");
          $("#img_job_error").html("");
          $(".action-remove-profile-image").hide();
        }
      },
    });
  });

  $(document).on("change", ".profile_image_upload", function () {
    var this_id = $(this).attr("id");
    var image_name = $(this).attr("image-name");
    var file_data = $("#" + this_id + "").prop("files")[0];
    var form_data = new FormData();
    form_data.append("file", file_data);
    form_data.append("type", "image");
    $("#img_job_error").html('<p class="error">Vent litt. Laster opp..</p>');
    $.ajax({
      url: "/user/Profile/profile_image_uploads",
      cache: false,
      contentType: false,
      processData: false,
      data: form_data,
      type: "post",
      success: function (php_script_response) {
        var data = jQuery.parseJSON(php_script_response);
        if (php_script_response != "") {
          if (data["success"] == "true") {
            $("#picture-holder").attr(
              "style",
              'background-image:url("' + data["imgurl"] + '");',
            );
            $("#img_job_error").html("");

            $(".action-remove-profile-image").show();
          } else {
            $("#img_job_error").html(data["msg"]);
          }
        }
      },
    });
  });
  $(document).ready(function () {
    $image_crop = $("#image_demo").croppie({
      enableExif: true,
      viewport: {
        width: 200,
        height: 200,
        type: "square",
      },
      boundary: {
        width: 300,
        height: 300,
      },
    });
    $(".profile_image_upload2").on("change", function () {
      var reader = new FileReader();
      reader.onload = function (event) {
        $image_crop
          .croppie("bind", {
            url: event.target.result,
          })
          .then(function () {
            console.log("jQuery bind complete");
          });
      };
      reader.readAsDataURL(this.files[0]);
      $("#uploadimageModal").modal("show");
    });
    $(".crop_image").click(function (event) {
      $image_crop
        .croppie("result", {
          type: "canvas",
          size: "viewport",
        })
        .then(function (response) {
          var file_name = $(".personal-info .number").html();
          $("#image_upload_101").val("");
          $.ajax({
            url: "/ajax/upload_profile_img",
            type: "POST",
            data: {
              image: response,
              file_name: file_name,
            },
            success: function (php_script_response) {
              $("#uploadimageModal").modal("hide");
              var data = jQuery.parseJSON(php_script_response);
              if (php_script_response != "") {
                if (data["success"] == "true") {
                  $("#picture-holder").attr(
                    "style",
                    'background-image:url("/' + data["imgurl"] + '");',
                  );
                  $("#img_job_error").html("");
                  $(".action-remove-profile-image").show();
                } else {
                  $("#img_job_error").html(data["msg"]);
                }
              }
            },
          });
        });
    });
  });
  $(document).on("click", ".ac-rotate", function (ev) {
    var src = $(".cr-image").attr("src");
    rotateBase64Image(src, "callback");
  });
  function rotateBase64Image(base64data, callback) {
    var offScreenCanvas = document.createElement("canvas");
    offScreenCanvasCtx = offScreenCanvas.getContext("2d");
    var img = new Image();
    img.src = base64data;
    offScreenCanvas.height = img.width;
    offScreenCanvas.width = img.height;
    offScreenCanvasCtx.rotate((90 * Math.PI) / 180);
    offScreenCanvasCtx.translate(0, -offScreenCanvas.width);
    offScreenCanvasCtx.drawImage(img, 0, 0);
    var img = offScreenCanvas.toDataURL("image/jpeg", 100);
    $(".cr-image").attr("src", img);
  }

  $(document).on("click", ".sortby-filter", function () {
    var val = $(this).val();
    var html = $(this).html();

    var map_address = $("#map_page_geo_address_desk").val();
    if (!(map_address == "" && val == 4)) {
      $("#orderbytext").attr("data-id", val);
      $("#orderbytext").html(html);
    }
  });

  $(document).on("click", "#search-title", function () {
    $("#search-title").val("");
  });
  $("#search-title").keydown(function (e) {
    if (e.keyCode == 13) {
      console.log("111");

      $(".search-data-filter").trigger("click");
    }
  });

  /**/
  $(document).on(
    "click",
    ".sortby-filter,.filter-job-input input,.filter-job-type input,.filter-location input,.search-data-filter-action-2",
    function () {
      var val = $(this).val();
      var map_address = $("#map_page_geo_address_desk").val();

      if (map_address == "" && val == 4) {
        $("#map_filter").modal("show");
        $(document).one(
          "keyup",
          "#popup_map_page_geo_address_details",
          function () {
            console.log("popup_map_page_geo_address : ....");
            $("#googleidsearch").val(this.id);
            globalinitMap_browse_popup();
          },
        );
      } else {
        let this_name = $(this).attr("name");
        if (
          this_name == "statusProfessional" ||
          this_name == "statusSmallJob"
        ) {
          var statusProfessional = $(
            "input:checkbox[name='statusProfessional']:checked",
          ).val();
          var statusSmallJob = $(
            "input:checkbox[name='statusSmallJob']:checked",
          ).val();

          if (
            statusProfessional === undefined ||
            statusProfessional === null ||
            statusProfessional == ""
          ) {
            statusProfessional = "";
          }
          if (
            statusSmallJob === undefined ||
            statusSmallJob === null ||
            statusSmallJob == ""
          ) {
            statusSmallJob = "";
          }

          checkbox_status_filter_desktop();
        }

        currentpage = 1;
        $("#currentpage").val(currentpage);
        manage_url(currentpage);

        setTimeout(function () {
          console.log("222");
          $(".search-data-filter").trigger("click");
        }, 400);
      }
    },
  );

  $(document).on("change", "#myRange", function () {
    currentpage = 1;
    $("#currentpage").val(currentpage);
    manage_url(currentpage);

    var DeviceType = $("body").attr("data-DeviceType");
    if (DeviceType != "mobile") {
      console.log("333");
      $(".search-data-filter").trigger("click");
    } else {
      filterMobile();
    }
  });

  $(document).on("click", ".btn-clear-job-filter-desk", function () {
    currentpage = 1;
    $("#currentpage").val(currentpage);
    manage_url(currentpage);

    $("#search-title").val("");
    $(".filter-job-type input,.filter-location input").prop("checked", false);
    $(".filter-job-type input,.filter-location input").removeAttr("checked");
    $("#myRange").val(250);

    console.log("444");

    $(".search-data-filter").trigger("click");
  });

  $(document).on("click", ".pagination-1 a,.pagination-1 button", function () {
    var currentpage = $(this).attr("currentpage");
    navigateToJobPage(currentpage);
  });

  $(document).on("change keypress", "#job-pagination-input", function (event) {
    if (
      event.type === "change" ||
      (event.type === "keypress" && event.which === 13)
    ) {
      var page = parseInt($(this).val());
      var totalpages = parseInt($("#totalpages").val());

      console.log("page::", page);
      console.log("totalpages::", totalpages);

      if (page >= 1 && page <= totalpages) {
        console.log("Nav to page :: yes");
        navigateToJobPage(page);
      }
    }
  });

  console.log("111dadfasdf--11");
  setTimeout(function () {
    $(".search-data-filter").trigger("click");
  }, 800);
});

function navigateToJobPage(currentpage) {
  console.log("currentpage:", currentpage);

  if (currentpage === undefined || currentpage === null) {
    return false;
  }

  $("#currentpage").val(currentpage);
  manage_url(currentpage);

  var search_title = $("#search-title").val();
  var myRange = $("#myRange").val();
  var map_address = $("#map_page_geo_address_desk").val();
  var map_zipcode = $("#map_page_geo_zipcode").val();
  var lat = $("#lat").val();
  var lng = $("#lng").val();
  var filter_state = [];
  $("input:checkbox[name='state']:checked").each(function () {
    var vals = $(this).val();
    filter_state.push(vals);
  });
  var filter_jobtype = [];
  $("input:checkbox[name='jobtype']:checked").each(function () {
    var vals = $(this).val();
    filter_jobtype.push(vals);
  });

  var statusProfessional = $(
    "input:checkbox[name='statusProfessional']:checked",
  ).val();
  var statusSmallJob = $("input:checkbox[name='statusSmallJob']:checked").val();
  if (
    statusProfessional === undefined ||
    statusProfessional === null ||
    statusProfessional == ""
  ) {
    statusProfessional = "";
  }
  if (
    statusSmallJob === undefined ||
    statusSmallJob === null ||
    statusSmallJob == ""
  ) {
    statusSmallJob = "";
  }

  var DeviceType = $("body").attr("data-DeviceType");
  var orderby = $("#orderbytext").attr("data-id");
  var url = "/browse/filter";

  var meta_location = "";
  var controller = $("body").attr("data-controller");
  if (controller == "browsesmalljob") {
    var url = "/browsesmalljob/filter";
    var meta_location = $("#meta_location").val();
  }

  $.ajax({
    url: url,
    method: "POST",
    data: {
      search_title: search_title,
      myRange: myRange,
      map_address: map_address,
      map_zipcode: map_zipcode,
      lat: lat,
      lng: lng,
      statusProfessional: statusProfessional,
      statusSmallJob: statusSmallJob,
      filter_jobtype: filter_jobtype,
      filter_state: filter_state,
      orderby: orderby,
      currentpage: currentpage,
      DeviceType: DeviceType,
      meta_location: meta_location,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        manage_url_for_category_location(currentpage, data["location_slug"]);

        $("#job_results").html(data["main_content"]);
        $("html, body").animate({ scrollTop: "40" }, 800);
      }
    },
  });
}

/*job-btn-update*/
$(document).on("click", ".btn-update-job-check", function () {
  var self_service_form = "";
  var self_service_form = $("#self_service_form").serializeArray();
  var jobFrm = $("#jobFrm").serializeArray();
  var imagess = [];
  $("#jobFrm input[name='image[]']").each(function () {
    var vals = $(this).val();
    imagess.push(vals);
  });
  var url = "/newjob/self_approve_check";
  $(".btn-update-job-check").html("Vent..");
  $("body").attr("frmtype", "update");
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobFrm: jobFrm,
      self_service_form: self_service_form,
      image: imagess,
      frmtype: "update",
    },
    dataType: "text",
    success: function (script_response) {
      $(".btn-update-job-check").html("Lagre");
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        /*$("#publish-job").addClass("publish-job-modal");*/
        $("#job_msg").html("");
        $("#publish-job").html(data["main_content"]);
        $("#publish-job").modal();
      } else {
        /* if (data['tr_to_zipcode'] == '1') {
                    $("input[name='tr_to_zipcode']").attr("type", "text");
                    $("#tr_to_zipcode_label").show();
                }
                if (data['tr_from_zipcode'] == '1') {
                    $("input[name='tr_from_zipcode']").attr("type", "text");
                    $("#tr_from_zipcode_label").show();
                }
				
				if (data['where_zipcode'] == '1') {
					$("input[name='where_zipcode']").attr("type", "text");
					$("#where_zipcode_label").show();
				} */

        if (data["tr_to_zipcode"] == "1") {
          $("input[name='tr_to_address']").val("");
        }
        if (data["tr_from_zipcode"] == "1") {
          $("input[name='tr_from_address']").val("");
        }
        if (data["where_zipcode"] == "1") {
          $("input[name='where_address']").val("");
        }

        $("#publish-job").modal("hide");
        $("#job_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});
/*job-btn-update*/

$(document).on("click", ".btn-update-job", function () {
  var jobFrm = $("#jobFrm").serializeArray();
  var self_service_form = $("#self_service_form").serializeArray();

  var imagess = [];
  $("#jobFrm input[name='image[]']").each(function () {
    var vals = $(this).val();
    imagess.push(vals);
  });
  var payment_type = $("input:radio[name='payment_type']:checked").val();

  $(".btn-update-job").html("Vent..");
  var url = "/newjob/updatejob";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobFrm: jobFrm,
      self_service_form: self_service_form,
      image: imagess,
    },
    dataType: "text",
    success: function (script_response) {
      /*  console.log(script_response); */
      $(".btn-update-job-check").html("Lagre");
      $("#action-job-manalApproval").html(
        '<i class="fas fa-eye" aria-hidden="true"></i> Manal approval',
      );
      $("#action-job-selfApproval").html(
        '<i class="fak fa-yencheck" aria-hidden="true"></i> Self Approve',
      );

      $("#job_msg").html("");
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("#job_msg").html(
          "<div class='response-msg alert alert-success'>" +
            data["message"] +
            "</div>",
        );
        window.location.href = "/myjobs";
      } else if (data["success"] == "deny_job") {
        /* $("#publish-job").removeClass("publish-job-modal");*/
        $("#publish-job").html(data["main_content"]);
      } else {
        /* if (data['tr_to_zipcode'] == '1') {
                    $("input[name='tr_to_zipcode']").attr("type", "text");
                    $("#tr_to_zipcode_label").show();
                }
                if (data['tr_from_zipcode'] == '1') {
                    $("input[name='tr_from_zipcode']").attr("type", "text");
                    $("#tr_from_zipcode_label").show();
                }
				
				if (data['where_zipcode'] == '1') {
					$("input[name='where_zipcode']").attr("type", "text");
					$("#where_zipcode_label").show();
				} */

        $("#job_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
        $("#publish-job").modal("hide");
      }
    },
  });
});

$(document).on(
  "change",
  'input[name="proposals_wanted_option_self_approve"]',
  function () {
    var proposals_wanted_option_self_approve = $(
      "input:checkbox[name='proposals_wanted_option_self_approve']:checked",
    ).val();
    if (proposals_wanted_option_self_approve == "1") {
      $("#Self-service-model").modal();
    }
  },
);

$(document).on("click", ".re-publish-job", function () {
  var id = $(this).attr("data-id");
  var url = "/newjob/republish";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      id: id,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        redirect_url = "/editjob?id=" + data["id"];
        window.location.href = redirect_url;
      }
    },
  });
});

/*btn-republish-job*/

$(document).on("click", ".btn-republish-job-check", function () {
  var self_service_form = "";
  var self_service_form = $("#self_service_form").serializeArray();
  var jobFrm = $("#jobFrm").serializeArray();
  var imagess = [];
  $("#jobFrm input[name='image[]']").each(function () {
    var vals = $(this).val();
    imagess.push(vals);
  });
  var url = "/newjob/self_approve_check";
  $(".btn-republish-job-check").html("Vent..");
  $("body").attr("frmtype", "republish");
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobFrm: jobFrm,
      self_service_form: self_service_form,
      image: imagess,
      frmtype: "republish",
    },
    dataType: "text",
    success: function (script_response) {
      $(".btn-republish-job-check").html("Lagre");
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        /*$("#publish-job").addClass("publish-job-modal");*/
        $("#job_msg").html("");
        $("#publish-job").html(data["main_content"]);
        $("#publish-job").modal();
      } else {
        $("#publish-job").modal("hide");
        $("#job_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});

/*btn-republish-job*/

$(document).on("click", ".btn-republish-job", function () {
  var self_service_form = $("#self_service_form").serializeArray();
  var jobFrm = $("#jobFrm").serializeArray();
  var imagess = [];
  $("#jobFrm input[name='image[]']").each(function () {
    var vals = $(this).val();
    imagess.push(vals);
  });

  $(".btn-republish-job").html("Vent...");
  $(".btn-republish-job").attr("disabled", "disabled");
  $(".btn-republish-job").prop("disabled", true);

  var url = "/newjob/republishjob";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      self_service_form: self_service_form,
      jobFrm: jobFrm,
      image: imagess,
    },
    dataType: "text",
    success: function (script_response) {
      /* console.log(script_response); */

      $(".btn-republish-job").removeAttr("disabled");

      $("#job_msg").html("");
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        /* 
				$("#job_msg").html("<div class='response-msg alert alert-success'>" + data['message'] + "</div>");
                window.location.href = "/myjobs"; 
				*/
        /* gtag_report_conversion(); */

        /*$("#publish-job").removeClass("publish-job-modal");*/

        $("#publish-job").html(data["main_content"]);
        $(".justify-content-end").remove();
        $(".job-btn-publish").remove();

        $("#publish-job").modal({
          backdrop: "static",
          keyboard: false,
        });
      } else {
        $("#job_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});
$(document).on("click", ".delete-img", function () {
  $(this).closest(".ajaximg").remove();
});
function countJob(job_id) {
  var url = "/browse/countView";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
    },
    dataType: "text",
    success: function (script_response) {},
  });
}

/*
$(document).on('click', '.btn-profile-helper', function () {
    var jobFrm = $("#jobFrm").serialize();
    var url = "user/register/profilehelper_formsubmit";
    $.ajax({
        url: url,
        method: "POST",
        data: {
            jobFrm: jobFrm,
        },
        dataType: "text",
        success: function (script_response) {
            
            $("#helper_msg").html("");
            var data = $.parseJSON(script_response);
            if (data['success'] == 'true') {
                $("#helper_msg").html("<div class='response-msg alert alert-success'>" + data['message'] + "</div>");
                if (data['redirect'] != '' && data['redirect'] !== null) {
                    window.location.href = '' + data['redirect'];
                }
            } else {
                $("#helper_msg").html("<div class='response-msg alert alert-danger'>" + data['message'] + "</div>");
            }
        }
    });
});
*/

/* $(document).on('click', '.btn-become-helper', function () {
    var jobFrm = $("#jobFrm").serialize();
    var url = "/registerhelper_formsubmit";
    $(".btn-become-helper").html("Vent...");
    $.ajax({
        url: url,
        method: "POST",
        data: {
            jobFrm: jobFrm,
        },
        dataType: "text",
        success: function (script_response) { 
            $("#helper_msg").html("");
            $(".btn-become-helper").html("Lagre endringer!");
            var data = $.parseJSON(script_response);
            if (data['success'] == 'true') {
                $("#helper_msg").html("<div class='response-msg alert alert-success'>" + data['message'] + "</div>");
                if (data['redirect'] != '' && data['redirect'] !== null) {
                    window.location.href = '' + data['redirect'];
                }
            } else {
                $("#helper_msg").html("<div class='response-msg alert alert-danger'>" + data['message'] + "</div>");
            }
        }
    });
}); */

$(document).on("click", ".btn-save-employer-profile", function () {
  var jobFrm = $("#jobFrm2").serialize();

  $(".btn-save-employer-profile").html("Vent..");
  /*  var url = "/updateprofile_formsubmit"; */
  var url = "user/register/employerprofile_update";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobFrm: jobFrm,
    },
    dataType: "text",
    success: function (script_response) {
      $("#employer_profile_msg").html("");
      $(".btn-save-employer-profile").html("Lagre endringer");
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $('input[name="newpassword"]').val("");

        if (data["message"] != "") {
          $("#employer_profile_msg").html(
            "<div class='response-msg alert alert-success'>" +
              data["message"] +
              "</div>",
          );
        } else {
          get_confirm_mail();
        }
      } else {
        $("#employer_profile_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});

$(document).on("click", ".btn-save-helper-profile", function () {
  $("#helper_profile_msg").html("");
  $(".btn-save-helper-profile").html("Vent..");

  var userFrm = $("#helperProfileFrm").serialize();

  var url = "user/register/helperprofile_update";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      userFrm: userFrm,
    },
    dataType: "text",
    success: function (script_response) {
      console.log(script_response);
      $(".btn-save-helper-profile").html("Send for godkjenning");
      $("#helper_profile_msg").html("");
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        setTimeout(function () {}, 400);
      } else {
        $("#helper_profile_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});

$(document).on("change", "#primary_category", function () {
  var jobtype_id = $(this).val();
  $("#primary_subcategory").html(
    '<option value="">Velg underkategori</option>',
  );

  if (jobtype_id === "") {
    return;
  }

  var url = "/newjob/ajax_jobsubtype";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobtype_id: jobtype_id,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("#primary_subcategory").html(
          '<option value="">Velg underkategori</option>' + data["main_content"],
        );
      }
    },
  });
});

$(document).on("click", ".btn-save-profile", function () {
  var jobFrm = $("#jobFrm2").serialize();
  var url = "/updateprofile_formsubmit";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobFrm: jobFrm,
    },
    dataType: "text",
    success: function (script_response) {
      $("#profile_msg").html("");
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        if (data["message"] != "") {
          $("#profile_msg").html(
            "<div class='response-msg alert alert-success'>" +
              data["message"] +
              "</div>",
          );
        } else {
          get_confirm_mail();
        }
        if (data["strex_status"] == "N") {
          $(".col-strex_status").html("");
        }
      } else {
        $("#profile_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});
$(document).on("click", ".btn-update-notification", function () {
  var jobFrm = $("#jobFrm").serialize();
  var url = "/notification_formsubmit";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobFrm: jobFrm,
    },
    dataType: "text",
    success: function (script_response) {
      /* console.log(script_response); */
      $("#helper_msg").html("");
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("#helper_msg").html(
          "<div class='response-msg alert alert-success'>" +
            data["message"] +
            "</div>",
        );
      } else {
        $("#helper_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});
$(document).on("click", ".btn-payment-again", function () {
  $("#success_payment").modal("hide");
  $("#funds-option").modal();
});

$(document).on("click", ".action-offer-help-step-1", function () {
  var job_id = $(this).attr("data-id");
  var url = "/browse/checkLogin";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        if (data["commonPopup"] == "true") {
          $("#commonModal").html(data["main_content"]);
          $("#commonModal").modal("show");
        } else {
          $("#payment-option-modal").html(data["main_content"]);
          $("#payment-option-modal").modal();
        }
      } else if (data["redirect"] != "") {
        window.location.href = "/" + data["redirect"];
      } else {
        window.location.href = "/innlogging";
      }
    },
  });
});

$(document).on("click", ".action-offer-help-step-1-confirm", function () {
  $(".action-offer-help-step-1-confirm").html("Vent..");

  var i_am_profesional = $('input[name="i_am_profesional"]:checked').val();

  var job_id = $(this).attr("data-id");
  var url = "/browse/offer_step_1_confirm";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
      i_am_profesional: i_am_profesional,
    },
    dataType: "text",
    success: function (script_response) {
      $(".action-offer-help-step-1-confirm").html(
        'Neste  <i class="fas fa-chevron-right" style="font-weight: bolder" aria-hidden="true"></i>',
      );

      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        if (data["commonPopup"] == "true") {
          $("#commonModal").html(data["main_content"]);
          $("#commonModal").modal("show");
        } else {
          $("#payment-option-modal").html(data["main_content"]);
          $("#payment-option-modal").modal();
        }
      } else if (data["success"] == "false" && data["message"] != "") {
        $("#funds_option_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
        setTimeout(function () {
          $("#funds_option_msg").html("");
        }, 10000);
      } else if (data["redirect"] != "") {
        window.location.href = "/" + data["redirect"];
      } else {
        window.location.href = "/innlogging";
      }
    },
  });
});

$(document).on("click", ".action-offer-help-eng", function () {
  var job_id = $(this).attr("data-id");
  var url = "/browse/checkLogin";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
      lang: "eng",
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("#payment-option-modal").html(data["main_content"]);
        /* $("#payment-option-modal").modal(); */
      } else if (data["redirect"] != "") {
        window.location.href = "/" + data["redirect"];
      } else {
        window.location.href = "/innlogging";
      }
    },
  });
});

/*
delete action-discuss-the-job
*/

$(document).on("click", ".action-discuss-the-job", function () {
  var job_id = $(this).attr("data-id");
  var invite_id = $("#invite_id").val();
  var url = "/browse/fundoption";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
      invite_id: invite_id,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("#payment-option-modal").html(data["main_content"]);
        $("#payment-option-modal").modal();
      } else {
        window.location.href = "/innlogging";
      }
    },
  });
});

$(document).on("click", ".btn-funds-option-back-2", function () {
  var job_id = $(this).attr("data-id");
  var url = "/browse/offerhelp_back";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("#payment-option-modal").html(data["main_content"]);
        $("#payment-option-modal").modal();
      } else {
        window.location.href = "/innlogging";
      }
    },
  });
});
$(document).on("click", 'input[name="payment_job_type"]', function () {
  var value = $(this).val();
  $(".options-suscription").removeClass("active");
  switch (value) {
    case "when-get-job":
      $(".options-suscription.one").addClass("active");
      break;
    case "inspection":
      $(".options-suscription.two").addClass("active");
      break;
  }
});
$(document).on("click", ".btn-funds-option-2", function () {
  $("#payment_msg_strex").html("");
  var payment_option_type = $(
    'input[name="payment_option_type"]:checked',
  ).val();

  var i_am_profesional = $('input[name="i_am_profesional"]').val();

  if (payment_option_type == "vipps") {
    $(".action-offer-help").trigger("click");
  }
  if (payment_option_type == "strex") {
    var job_id = $("#job_id").val();
    var invite_id = $("#invite_id").val();
    var acceptInfo = $('input[name="acceptInfo"]:checked').val();

    var url = "/payment/offerhelp_stex";
    $(".btn-funds-option-2").html("Vent..");
    if ($(".btn-funds-option-2").is("[disabled=disabled]") == false) {
      $(".btn-funds-option-2").attr("disabled", "disabled");
      $.ajax({
        url: url,
        method: "POST",
        data: {
          job_id: job_id,
          invite_id: invite_id,
          acceptInfo: acceptInfo,
          i_am_profesional: i_am_profesional,
        },
        dataType: "text",
        success: function (script_response) {
          var data = $.parseJSON(script_response);
          /* console.log(data['success']); */

          $(".btn-funds-option-2").html(
            'Neste <i class="fas fa-chevron-right" style="font-weight: bolder" aria-hidden="true"></i>',
          );
          if (data["success"] == "true") {
            var job_id = $("#job_id").val();
            window.location.href =
              "/messages?chat_id=" + data["user_id"] + "&job_id=" + job_id + "";
          } else if (data["success"] == "popup") {
            $("#payment-option-modal").html(data["main_content"]);
            $(".btn-funds-option-2").removeAttr("disabled");
          } else if (data["success"] == "popupstrex") {
            var currentId = $(".modal.fade.show").attr("id");
            $("#stex_popupstrex").attr("pre_id", currentId);
            $("#payment-option-modal").html(data["main_content"]);
            $(".btn-funds-option-2").removeAttr("disabled");
          } else {
            if (data["redirect"] != "" && data["message"] == "") {
              window.location.href = "/" + data["redirect"];
            } else if (data["message"] == "") {
              data["message"] = "Noe gikk galt. Prøv igjen senere.";
            }
            $("#payment_msg_strex").html(
              "<div class='response-msg alert alert-danger'>" +
                data["message"] +
                "</div>",
            );
            $(".btn-funds-option-2").removeAttr("disabled");
          }
        },
      });
    }
  }
});
$(document).on("click", ".action-offer-funds-option-espection-2", function () {
  $("#payment_msg_strex").html("");
  var payment_option_type = $(
    'input[name="payment_option_type"]:checked',
  ).val();
  /* console.log(payment_option_type); */
  if (payment_option_type == "vipps") {
    var offerinfo = $("#offer-info-popup").serialize();
    var url = "/payment/addtilbud_option3";
    $(".action-offer-funds-option-espection-2").html("Vent..");
    $.ajax({
      url: url,
      method: "POST",
      data: {
        offerinfo: offerinfo,
      },
      dataType: "text",
      success: function (script_response) {
        var data = $.parseJSON(script_response);
        $(".action-offer-funds-option-espection-2").html(
          'Neste <i class="fas fa-chevron-right" style="font-weight: bolder" aria-hidden="true"></i>',
        );
        if (data["success"] == "true") {
          $("#add-funds-suggestions #payment_msg_strex").html("");
          $("#add-funds-suggestions .modal-body").html(data["main_content"]);
        } else {
          $("#add-funds-suggestions #payment_msg_strex").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );
        }
        setTimeout(function () {
          $("#add-funds-suggestions #payment_msg_strex").html("");
        }, 12000);
      },
    });
  }
  if (payment_option_type == "strex") {
    var offerinfo = $("#offer-info-popup").serialize();
    var url = "/payment/offerhelp_stex2";
    $(".action-offer-funds-option-espection-2").html("Vent..");
    if (
      $(".action-offer-funds-option-espection-2").is("[disabled=disabled]") ==
      false
    ) {
      $(".action-offer-funds-option-espection-2").attr("disabled", "disabled");
      $.ajax({
        url: url,
        method: "POST",
        data: {
          offerinfo: offerinfo,
          payment_job_type: "inspection",
        },
        dataType: "text",
        success: function (script_response) {
          /*  console.log(JSON.stringify(script_response)); */
          var data = $.parseJSON(script_response);
          $(".action-offer-funds-option-espection-2").html(
            'Neste <i class="fas fa-chevron-right" style="font-weight: bolder" aria-hidden="true"></i>',
          );
          if (data["success"] == "true") {
            var job_id = $("#job_id").val();
            window.location.href =
              "/messages?chat_id=" + data["user_id"] + "&job_id=" + job_id + "";
          } else if (data["success"] == "popupstrex") {
            var currentId = $(".modal.fade.show").attr("id");
            $("#stex_popupstrex").attr("pre_id", currentId);
            $("#payment-option-modal").html(data["main_content"]);
            $(".action-offer-funds-option-espection-2").removeAttr("disabled");
          } else if (data["success"] == "popup") {
            $("#payment-option-modal").html(data["main_content"]);
            $(".action-offer-funds-option-espection-2").removeAttr("disabled");
          } else {
            $("#offer-info-popup #payment_msg_strex").html(
              "<div class='response-msg alert alert-danger'>" +
                data["message"] +
                "</div>",
            );
            $(".action-offer-funds-option-espection-2").removeAttr("disabled");
          }
        },
      });
    }
  }
});

$(document).on("click", "#continue_confirm_number", function () {
  var job_id = $("#job_id").val();
  var confirm_number = $("#confirm_number").val();
  var transactionId = $("#transactionId").val();
  var payment_job_type = $('input[name="payment_job_type"]:checked').val();
  var invite_id = $("#invite_id").val();
  var offerinfo = $("#offer-info-popup").serialize();
  $("#continue_confirm_number").html("Vent..");
  var url = "/payment/offerhelp_stex_confirm";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
      invite_id: invite_id,
      confirm_number: confirm_number,
      transactionId: transactionId,
      payment_job_type: payment_job_type,
      offerinfo: offerinfo,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      $("#continue_confirm_number").html("Neste >");

      console.log(data["success"]);

      if (data["success"] == "true") {
        $("#payment-option-modal").html(data["main_content"]);
        $("#user_id").val(data["user_id"]);
      } else if (data["success"] == "popupstrex") {
        var currentId = $(".modal.fade.show").attr("id");
        $("#stex_popupstrex").attr("pre_id", currentId);
        $(".modal").modal("hide");
        $("#stex_popupstrex").modal("show");
        $("#continue_confirm_number").removeAttr("disabled");
      } else {
        $("#confirm_number_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      $("#confirm_number_msg").html(
        "<div class='response-msg alert alert-danger'> " +
          textStatus +
          ": Noe gikk galt.</div>",
      );
    },
  });
});
$(document).on("click", "#offerhelp_stex_confirm_next", function () {
  var job_id = $("#job_id").val();
  var user_id = $("#user_id").val();
  window.location.href =
    "/messages?chat_id=" + user_id + "&job_id=" + job_id + "";
});
$(document).on("click", ".action-offer-help", function () {
  $(".btn-funds-option-2").html("Vent..");

  var job_id = $(this).attr("data-id");
  var payment_option_type = $(
    'input[name="payment_option_type"]:checked',
  ).val();
  var invite_id = $("#invite_id").val();
  var acceptInfo = $('input[name="acceptInfo"]:checked').val();
  var i_am_profesional = $('input[name="i_am_profesional"]').val();

  var url = "/browse/offerhelp";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
      payment_option_type: payment_option_type,
      invite_id: invite_id,
      acceptInfo: acceptInfo,
      i_am_profesional: i_am_profesional,
    },
    dataType: "text",
    success: function (script_response) {
      $("#payment_msg_strex").html("");

      $(".btn-funds-option-2").html(
        'Neste <i class="fas fa-chevron-right" style="font-weight: bolder" aria-hidden="true"></i>',
      );

      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("#payment-option-modal").html(data["main_content"]);
        $("#payment-option-modal").modal();
      } else {
        if (data["redirect"] != "" && data["redirect"] !== null) {
          window.location.href = "/" + data["redirect"];
        } else {
          $("#payment_msg_strex").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );
        }
      }
    },
  });
});

$(document).on("click", ".action-add-pending-payment", function () {
  $("#payment_msg").html("");
  var paymentInfo = $("#payment-info").serialize();
  var invite_id = $("#invite_id").val();

  var url = "/payment/add_pending_payment";
  var btn_add_payment = $(".action-add-pending-payment").html();
  $(".action-add-pending-payment").html("Vent..");
  $.ajax({
    url: url,
    method: "POST",
    data: {
      paymentInfo: paymentInfo,
      invite_id: invite_id,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      $(".action-add-pending-payment").html(btn_add_payment);
      if (data["success"] == "true") {
        window.location.href = data["url"];
      } else {
        $("#payment_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
      setTimeout(function () {
        $("#payment_msg").html("");
      }, 12000);
    },
  });
});

$(document).on("click", ".btn-add-payment", function () {
  $("#payment_msg").html("");
  var paymentInfo = $("#payment-info").serialize();
  var invite_id = $("#invite_id").val();

  var url = "/payment/addpayment";
  var btn_add_payment = $(".btn-add-payment").html();
  $(".btn-add-payment").html("Vent..");
  $.ajax({
    url: url,
    method: "POST",
    data: {
      paymentInfo: paymentInfo,
      invite_id: invite_id,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      $(".btn-add-payment").html(btn_add_payment);
      if (data["success"] == "true") {
        window.location.href = data["url"];
      } else {
        $("#payment_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
      setTimeout(function () {
        $("#payment_msg").html("");
      }, 12000);
    },
  });
});
$(document).on("click", ".action-espection-payment", function () {
  $("#payment_msg").html("");
  var paymentInfo = $("#payment-info").serialize();
  var url = "/payment/addpayment_espection";
  var btn_add_payment = $(".btn-add-payment").html();
  $(".action-espection-payment").html("Vent..");
  $.ajax({
    url: url,
    method: "POST",
    data: {
      paymentInfo: paymentInfo,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      $(".action-espection-payment").html(btn_add_payment);
      if (data["success"] == "true") {
        window.location.href = data["url"];
      } else {
        $("#payment_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
      setTimeout(function () {
        $("#payment_msg").html("");
      }, 12000);
    },
  });
});
$(document).on("click", ".action-request-inspection", function () {
  var job_id = $(this).attr("data-id");
  var url = "/browse/request_inspection";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("#payment-option-modal").html(data["main_content"]);
        $("#payment-option-modal").modal();
      } else {
        window.location.href = "/innlogging";
      }
    },
  });
});
$(document).on("click", ".action-job-details-model", function () {
  var job_id = $(this).attr("data-id");
  var url = "/browse/job_details_model";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("#payment-option-modal").html(data["main_content"]);
        $("#payment-option-modal").modal();
      } else {
        window.location.href = "/innlogging";
      }
    },
  });
});
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
  directionsService.route(
    {
      origin: document.getElementById("tr_from_address").value,
      destination: document.getElementById("tr_to_address").value,
      travelMode: "DRIVING",
    },
    function (response, status) {
      if (status === "OK") {
        directionsDisplay.setDirections(response);
      } else {
        console.log("Directions request failed due to " + status);
      }
    },
  );
}
function initMap() {
  var DeviceType = $("body").attr("data-DeviceType");
  if (DeviceType == "mobile") {
    var location_status = $('input[name = "location_status"]').val();
  } else {
    var location_status = $('input[name = "location_status"]:checked').val();
  }

  console.log("initMap = location status = " + location_status);
  if (location_status == "2" || location_status == "3") {
    initMap3();
  } else if ($("#where_address").length > 0) {
    initMap2();
  } else {
    console.log("step=initMap");
    var directionsService = new google.maps.DirectionsService();
    var directionsDisplay = new google.maps.DirectionsRenderer();
    var map = new google.maps.Map(document.getElementById("map"), {
      zoom: 6,
      center: {
        lat: 60.472,
        lng: 8.4689,
      },
    });
    directionsDisplay.setMap(map);
    var onChangeHandler = function () {
      calculateAndDisplayRoute(directionsService, directionsDisplay);
    };
    document
      .getElementById("tr_from_address")
      .addEventListener("change", onChangeHandler);
    document
      .getElementById("tr_to_address")
      .addEventListener("change", onChangeHandler);
    var origin = document.getElementById("tr_from_address").value;
    var destination = document.getElementById("tr_to_address").value;
    if (origin != "" && destination != "") {
      setTimeout(function () {
        calculateAndDisplayRoute(directionsService, directionsDisplay);
      }, 200);
    }
  }
}

var geocoder;
var map;
function initMap2() {
  console.log("step=initMap2");

  var map = new google.maps.Map(document.getElementById("map"), {
    zoom: 6,
    center: {
      lat: 60.472,
      lng: 8.4689,
    },
  });
  geocoder = new google.maps.Geocoder();
  codeAddress(geocoder, map);
}
function initMap3() {
  console.log("step=initMap3");

  var map = new google.maps.Map(document.getElementById("map"), {
    zoom: 6,
    center: {
      lat: 60.472,
      lng: 8.4689,
    },
  });
  geocoder = new google.maps.Geocoder();
  codeAddress3(geocoder, map);
}

function codeAddress(geocoder, map) {
  console.log("step=codeAddress");

  setTimeout(function () {
    var address = document.getElementById("where_address").value;

    if (
      $("#any_location_status").length > 0 &&
      !$("#any_location_status").is(":checked")
    ) {
      var address = "Norway";

      geocoder.geocode(
        {
          address: address,
        },
        function (results, status) {
          if (status === "OK") {
            $("#map").html(
              '<iframe src="https://www.google.com/maps/embed/v1/place?key=AIzaSyCU1tNU9h5_B-EKd0WHTBn8aTmFlTiVem8&q=' +
                address +
                '&maptype=roadmap&zoom=4" width="100%" height="400" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" style="border:0;" allowfullscreen=""></iframe>',
            );
          } else {
          }
        },
      );
    } else {
      geocoder.geocode(
        {
          address: address,
        },
        function (results, status) {
          if (status === "OK") {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
              map: map,
              position: results[0].geometry.location,
            });
          } else {
            /* alert('Geocode was not successful for the following reason: ' + status); */
          }
        },
      );
    }
  }, 500);
}

function codeAddress3(geocoder, map) {
  console.log("step=codeAddress3");
  setTimeout(function () {
    var address = document.getElementById("tr_from_address").value;

    geocoder.geocode(
      {
        address: address,
      },
      function (results, status) {
        if (status === "OK") {
          map.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location,
          });
        } else {
          /* alert('Geocode was not successful for the following reason: ' + status); */
        }
      },
    );
  }, 500);
}

$(document).on("change", "#where_address", function () {
  /* initMap2(); */

  if (
    $("#any_location_status").length > 0 &&
    !$("#any_location_status").is(":checked")
  ) {
    var url = "/ajax/get_norway_map";
    $.ajax({
      url: url,
      method: "POST",
      data: {},
      dataType: "text",
      success: function (script_response) {
        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          $("#map").html(data["map"]);
        } else {
        }
      },
    });
  } else {
    initMap2();
  }
});

$(document).on("change", "#tr_to_address,#tr_from_address", function () {
  var DeviceType = $("body").attr("data-DeviceType");
  if (DeviceType == "mobile") {
    var location_status = $('input[name = "location_status"]').val();
  } else {
    var location_status = $('input[name = "location_status"]:checked').val();
  }

  if (location_status == "2" || location_status == "3") {
    initMap3();
  } else {
    var origin = document.getElementById("tr_from_address").value;
    var destination = document.getElementById("tr_to_address").value;
    if (origin != "" && destination != "") {
      initMap();
    }
  }
});

$(document).on("click", ".job-budget_price-change", function () {
  var url = "/newjob/send_change_budget";
  var job_id = $("#job_id").val();
  var budget_price = $("#budget_price").val();
  $(".job-budget_price-change").html("Vent..");
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
      budget_price: budget_price,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      $(".job-budget_price-change").html("Save");
      if (data["success"] == "true") {
        $("#job-unpublished-msg").html(
          "<div class='response-msg alert alert-success alert-dismissible' >" +
            data["message"] +
            "</div>",
        );
      } else {
        $("#job-unpublished-msg").html(
          "<div class='response-msg alert alert-danger alert-dismissible' >" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});

$(document).on("click", ".action-job-unpublished", function () {
  $(".action-job-unpublished").html("Vent..");

  var url = "/ajax/action_job_unpublished";
  var job_id = $("#job_id").val();
  var type = $("#type").val();
  var message = $("#message").val();

  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
      type: type,
      message: message,
    },
    dataType: "text",
    success: function (script_response) {
      $(".action-job-unpublished").html("Send");

      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("textarea").val("");
        $("#job-unpublished-msg").html(
          "<div class='response-msg alert alert-success alert-dismissible' >" +
            data["message"] +
            "</div>",
        );
      } else {
        $("#job-unpublished-msg").html(
          "<div class='response-msg alert alert-danger alert-dismissible' >" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});

$(document).on(
  "click",
  ".action-update-price,.action-update-description",
  function () {
    $(".action-update-price").html("Vent..");
    $(".action-update-description").html("Vent..");

    var url = "/ajax/action_unpublished_change_password";
    var job_id = $("#job_id").val();
    var change_price = $("#change_price").val();
    var type = $("#type").val();
    var description = $("#job_description").val();

    if ($(event.target).hasClass("action-update-description")) {
      var type = 2;
    } else {
      var type = 1;
    }

    $.ajax({
      url: url,
      method: "POST",
      data: {
        job_id: job_id,
        change_price: change_price,

        description: description,

        type: type,
      },
      dataType: "text",
      success: function (script_response) {
        $(".action-update-price").html("Update");
        $(".action-update-description").html("Update");

        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          $("#change_price").val("");

          $(".job-unpublished2-msg").html(
            "<div class='response-msg alert alert-success alert-dismissible' >" +
              data["message"] +
              "</div>",
          );
        } else {
          $(".job-unpublished2-msg").html(
            "<div class='response-msg alert alert-danger alert-dismissible' >" +
              data["message"] +
              "</div>",
          );
        }
      },
    });
  },
);

$(document).on("click", ".job-unpublished-message", function () {
  var url = "/ajax/send_unpublished_msg";
  var job_id = $("#job_id").val();
  var message = $("#message").val();

  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
      message: message,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("textarea").val("");
        $("#job-unpublished-msg").html(
          "<div class='response-msg alert alert-success alert-dismissible' >" +
            data["message"] +
            "</div>",
        );
      } else {
        $("#job-unpublished-msg").html(
          "<div class='response-msg alert alert-danger alert-dismissible' >" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});

$(document).on("click", ".user-unpublished-message", function () {
  var url = "/ajax/send_unpublished_msg_user";
  var user_id = $("#user_id").val();
  var message = $("#message").val();
  $.ajax({
    url: url,
    method: "POST",
    data: {
      user_id: user_id,
      message: message,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("textarea").val("");
        $("#job-unpublished-msg").html(
          "<div class='response-msg alert alert-success alert-dismissible' >" +
            data["message"] +
            "</div>",
        );
      } else {
        $("#job-unpublished-msg").html(
          "<div class='response-msg alert alert-danger alert-dismissible' >" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});
$(document).on("click", ".btn-Kundeservice", function () {
  var jobFrm = $("#formKundeservice").serialize();
  var url = "/ajax/formKundeservice";
  $(".btn-Kundeservice").html("Vent..");
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobFrm: jobFrm,
      captcha: grecaptcha.getResponse(),
    },
    dataType: "text",
    success: function (script_response) {
      /* console.log(script_response); */
      $(".btn-Kundeservice").html("Send melding");
      grecaptcha.reset();
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("#Kundeservice_msg").html(
          "<div class='response-msg alert alert-success'>" +
            data["message"] +
            "</div>",
        );
        $("#formKundeservice input").val("");
      } else {
        $("#Kundeservice_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});
$(document).on("click", ".btn-login-frm", function () {
  $("#loginFrm").submit();
  /*
  var loginFrm = $("#loginFrm").serialize();
  var url = "/user/login/check_user_email_active";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobFrm: loginFrm,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "false") {
        $("#email-verify").modal();
        $("#email").val(data["email_address"]);
        $("#user_id").val(data["user_id"]);
      } else {
        $("#loginFrm").submit();
      }
    },
  });
  */
});

$("#loginFrm input").keydown(function (e) {
  if (e.keyCode == 13) {
    $(".btn-login-frm").trigger("click");
  }
});

$(document).on("click", ".action-new-confirm-mail", function () {
  get_confirm_mail();
});
function get_confirm_mail() {
  var email_address = $("#validationServerUserEmail").val();
  var url = "/user/login/new_confirm_mail";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      email_address: email_address,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "false") {
        $("#employer_profile_msg").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      } else {
        $(".btn-save-employer-profile").remove();
        $("#employer_profile_msg").html(
          "<div class='response-msg alert alert-success'>" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
}
$(document).on("click", ".btn-formemailverify", function () {
  var loginFrm = $("#formemailverify").serialize();
  var url = "/user/login/sent_user_verify_email";
  $(".btn-formemailverify").html("Vent..");
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobFrm: loginFrm,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      $(".btn-formemailverify").html("Send på nytt");
      if (data["success"] == "false") {
        $("#msg-formemailverify").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      } else {
        $("#msg-formemailverify").html(
          "<div class='response-msg alert alert-success'>" +
            data["message"] +
            "</div>",
        );
        $(".btn-formemailverify").remove();
      }
    },
  });
});
$(document).on("click", ".btn-bugreport", function () {
  var jobFrm = $("#formbugreport").serialize();
  var url = "/ajax/bugreport";
  $(".btn-bugreport").html("Vent..");
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobFrm: jobFrm,
    },
    dataType: "text",
    success: function (script_response) {
      /* console.log(script_response); */
      $(".btn-bugreport").html("Send melding");
      grecaptcha.reset();
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("#msg-bugreport").html(
          "<div class='response-msg alert alert-success'>" +
            data["message"] +
            "</div>",
        );
        $("#formbugreport input").val("");
      } else {
        $("#msg-bugreport").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});
$(document).on("click", ".btn-bugreport-pannel-close", function () {
  $("#report-pannel").modal("hide");
});
$(document).on("click", ".btn-bugreport-pannel", function () {
  var jobFrm = $("#formreportpannel").serialize();
  var url = "/ajax/bugreportpannel";
  $(".btn-bugreport-pannel").html("Vent..");
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobFrm: jobFrm,
    },
    dataType: "text",
    success: function (script_response) {
      /* console.log(script_response); */
      $(".btn-bugreport-pannel").html("Rapporter");
      grecaptcha.reset();
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        /*
        $("#report-pannel .modal-body").html(
          '<div class="information-popup" style=""><div class="wrapme" style="max-width:560px;margin: auto;"><h2 style="">Takk for at du rapporterer</h2><p style="">Vi har mottatt meldingen og kommer om kort tid til å sjekke annonsen og fjerne den om den ikke følger vårt regelverk. Ta kontakt med kundeservice om du har spørsmål.</p><p></p><p class="text-center"><a href="javascript:;" class="btn btn-primary btn-bugreport-pannel-close">Lukk</a></p></div></div>'
        );
		*/

        $("#report-pannel .modal-title").html("Tusen takk!");

        $("#report-pannel .modal-body").html(
          '<div class="information-popup" style=""><div class="wrapme" style="max-width:560px;margin: auto;"><p style="">Vi har mottatt meldingen og kommer om kort tid til å sjekke annonsen og fjerne den om den ikke følger vårt regelverk. Ta kontakt med kundeservice om du har spørsmål.</p><p></p><p class="text-center"><a href="javascript:;" class="btn btn-primary btn-bugreport-pannel-close">Lukk</a></p></div></div>',
        );
        $("#formreportpannel textarea").val("");
      } else {
        $("#msg-bugreportpannel").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});
$(document).on("click", ".btn-change-password", function () {
  var jobFrm = $("#form-pass").serializeArray();
  let createpassword1 = $("#createpassword-1").val();

  var url = "/user/login/change_password";
  if ($(this).html() == "Ferdig") {
    $("#password-change").modal("hide");
    return false;
  }
  $(".btn-change-password").html("Vent..");
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobFrm: jobFrm,
      createpassword1: createpassword1,
    },
    dataType: "text",
    success: function (script_response) {
      /* console.log(script_response); */
      $(".btn-change-password").html("Lagre");
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $("#msg_change_password").html(
          "<div class='response-msg alert alert-success'>" +
            data["message"] +
            "</div>",
        );
        $(".btn-change-password").html("Ferdig");
      } else {
        $("#msg_change_password").html(
          "<div class='response-msg alert alert-danger'>" +
            data["message"] +
            "</div>",
        );
      }
    },
  });
});

$(document).on("click", ".action-keep-password-confirm", function () {
  $("#password-change").modal("hide");
  var url = "/user/login/keep_password";
  $.ajax({
    url: url,
    method: "POST",
    data: {},
    dataType: "text",
    success: function (script_response) {},
  });
});

/*cancel job*/
$(document).on("click", ".action-cancel-job", function () {
  var job_id = $("#job_id").val();
  let type = 1;
  if (typeof job_id == "undefined" || job_id == "") {
    var job_id = $(this).attr("data-job_id");
    type = 2;
  }

  var url = "/user/editjob/cancel_job_step1";
  $(".action-cancel-job").html("Vent..");
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
    },
    dataType: "text",
    success: function (script_response) {
      $(".action-cancel-job").html("Klikk her");
      if (type == 2) {
        $(".action-cancel-job").html(
          'Kanseller oppdraget <i class="fas fa-ban"></i>',
        );
      }

      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        /*  $("#cancel-job").html(data['main_content']);
				 $("#cancel-job").modal('show');  */

        $("#commonModal").html(data["main_content"]);
        $("#commonModal").modal("show");
      } else {
        alert("Ooops! Noe gikk galt. Prøv igjen litt senere.");
      }
    },
  });
});

/*cancel job*/

$(document).on("click", ".btn-cancel-job", function () {
  /* var job_id = $("#job_id").val(); */

  var job_id = $(this).attr("job_id");
  console.log(job_id);

  var url = "/user/editjob/cancel_job";
  $(".btn-cancel-job").html("Vent..");
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
    },
    dataType: "text",
    success: function (script_response) {
      $(".btn-cancel-job").html("Kanseller jobben");
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        /* $(".information-popup-hide").hide();
                $(".information-popup-show").show(); */
        /*  $("#cancel-job").html(data['main_content']); */
        $("#commonModal").html(data["main_content"]);
      } else {
        alert("Ooops! Noe gikk galt. Prøv igjen litt senere.");
      }
    },
  });
});
function notify_job_award(job_id) {
  var url = "/messages/notify_job_award";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      job_id: job_id,
    },
    dataType: "text",
    success: function (script_response) {},
  });
}
$(function () {
  /* $("#datepicker").datepicker({
        minDate: 0,
        dateFormat: 'dd-mm-yy'
    }); */

  $("#datepicker").datepicker({
    minDate: 0,
    dateFormat: "dd.mm.yy",
  });
});
$(document).on("change", "select[name=time]", function () {
  getTimeOpt();
});
$(document).on("click", ".m-filter-job-type input", function () {
  var checked_here = "";
  if ($(this).is(":checked")) {
    checked_here = "1";
  }
  $(".m-filter-job-type input").prop("checked", false);
  if (checked_here == "1") {
    $(this).prop("checked", true);
  }
  var id = $(this).attr("data-targetid");
  $("#" + id + "").trigger("click");
});
$(document).on(
  "click",
  ".btn-filter-job-type,.btn-filter-location",
  function () {
    console.log("5555");

    $(".search-data-filter").trigger("click");
    $("#filtertypemodal,#filterlocationmodal").modal("hide");
  },
);
$(document).on("click", ".btn-link-job-li", function () {
  $(".filter-group input").prop("checked", false);
  $(".filter-group input").removeAttr("checked");
  var id = $(this).attr("data-target");
  setTimeout(function () {
    if ($("" + id + "").hasClass("show")) {
      $("" + id + " input").prop("checked", true);
      $("" + id + " input").attr("checked", "checked");
    }
    currentpage = 1;
    $("#currentpage").val(currentpage);
    manage_url(currentpage);

    console.log("1116999");
    $(".search-data-filter").trigger("click");
  }, 400);
});
$(document).on("click", ".btn-clear-job-filter", function () {
  $(".filters").trigger("click");
  $("html, body").animate({ scrollTop: 0 }, "slow");
});
function getTimeOpt() {
  var val = $("select[name=time]").val();
  if (val == 3 || val == 4) {
    $(".dato-cs").show();
  } else {
    $(".dato-cs").hide();
  }
}
getTimeOpt();
function gtag_report_conversion(url) {
  var callback = function () {
    if (typeof url != "undefined") {
      window.location = url;
    }
  };
  gtag("event", "conversion", {
    send_to: "AW-736812779/z9RPCJ21u6kBEOu9q98C",
    transaction_id: "",
    event_callback: callback,
  });
  return false;
}
$(function () {
  $(".notificationscheck").change(function () {
    $(".notificaationsopr").slideToggle();
  });
  $(document).on(
    "change",
    "input[name = 'total_payment'],input[name = 'payment_per_hour']",
    function () {
      var val = $(this).val();
      val = val.replace(/[^\d]*/gi, "");
      $(this).val(val);
    },
  );
  $(document).on(
    "keyup",
    "input[name = 'total_payment'],input[name = 'payment_per_hour']",
    function () {
      var val = $(this).val();
      val = val.replace(/[^\d]*/gi, "");
      $(this).val(val);
    },
  );
});
if ($("#password-change").length) {
  $("#password-change").modal();
}

if ($("#activation-status-popup").length) {
  $("#activation-status-popup").modal();
}

/* if ($('#success_payment').length) {
    $("#success_payment").modal();
} */
$(document).on("click", ".btn-close-payment", function () {
  $("#success_payment").modal("hide");
});
$(document).on("click", ".btn-payment-again-offer", function () {
  $("#success_payment").modal("hide");
  $("#add-funds-suggestions").modal("show");
});
$(document).on("click", ".cancel-job-close", function () {
  window.location.href = "/myjobs";
});

/*
$(document).on("click", ".enter-reserverd-pay-msg", function () {
  if ($("#success_payment").length) {
    var payment_info = $("#payment-info2").serialize();
    var user_id = $(".selected-listing").attr("data-user_id");
    var job_id = $(".selected-listing").attr("data-job_id");
    var helper = $(".selected-listing").attr("data-helper");
    var url = "/messages/enterpaymsg";
    $.ajax({
      url: url,
      method: "POST",
      data: {
        user_id: user_id,
        job_id: job_id,
        helper: helper,
        payment_info: payment_info,
      },
      dataType: "text",
      success: function (script_response) {
        var data = $.parseJSON(script_response);
        if (data["success"] == "true") {
          $("#payment_message").val("");
          $("#success_payment").modal("hide");
          $("#success_payment_msg").html("");
        } else {
          $("#success_payment_msg").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>"
          );
        }
      },
    });
  }
});
*/

function checkbox_status_filter_desktop() {
  var statusProfessional = $(
    "input:checkbox[name='statusProfessional']:checked",
  ).val();
  var statusSmallJob = $("input:checkbox[name='statusSmallJob']:checked").val();

  if (
    statusProfessional === undefined ||
    statusProfessional === null ||
    statusProfessional == ""
  ) {
    statusProfessional = "";
  }
  if (
    statusSmallJob === undefined ||
    statusSmallJob === null ||
    statusSmallJob == ""
  ) {
    statusSmallJob = "";
  }

  console.log("statusProfessional:", statusProfessional);
  console.log("statusSmallJob:", statusSmallJob);

  if (statusProfessional == "" && statusSmallJob == "") {
    $("input:checkbox[name='statusProfessional']").prop("checked", true);
    $("input:checkbox[name='statusSmallJob']").prop("checked", true);
  }
}

$(function () {
  $("#search").click(function () {
    $(".search-holder").slideToggle("");
    document.getElementById("search-title-mobile").focus();
  });
  $(".filters").click(function () {
    $(".new-filters").slideToggle("slow");
    $(".search-holder").slideUp();
  });
  $(".filters-login").click(function () {
    $("#filters-login").modal("show");
  });
});
$(document).on("blur", "#map_page_geo_address_desk", function () {
  var map_address = $("#map_page_geo_address_desk").val();
  if (map_address == "") {
    var map_address_p = $("body").attr("map_address");
    if (map_address_p != "") {
      $("#map_page_geo_address_desk").val(map_address_p);
    }
  }
});
$(document).on(
  "click",
  ".action-search-inputs-label-1 .close,.action-close-map",
  function () {
    $("#map_page_geo_address_desk").val("");
    $("#map_page_geo_zipcode").val("");
    $("#lat").val("");
    $("#lng").val("");
    $(".action-search-inputs-label-1 p").html("");
    $(".action-search-inputs-label-1").attr("style", "display:none !important");

    var val = 1;
    var html = "Siste";
    $("#orderbytext").attr("data-id", val);
    $("#orderbytext").html(html);

    console.log("666");

    setTimeout(function () {
      $(".search-data-filter").trigger("click");
    }, 100);
  },
);

$(document).on("click", ".action-clear-map-address", function () {
  $("#map_page_geo_address_desk").val("");
});

$(document).on("click", ".action-search-inputs-label-2 .close", function () {
  console.log("7777");

  $("#search-title").val("");
  setTimeout(function () {
    $(".search-data-filter").trigger("click");
  }, 100);
});

$(document).on("click", ".action-search-inputs-label-3 .close", function () {
  $("input:checkbox[name='statusProfessional']").prop("checked", false);

  checkbox_status_filter_desktop();
  setTimeout(function () {
    $(".search-data-filter").trigger("click");
  }, 100);
});
$(document).on("click", ".action-search-inputs-label-4 .close", function () {
  $("input:checkbox[name='statusSmallJob']").prop("checked", false);
  checkbox_status_filter_desktop();
  setTimeout(function () {
    $(".search-data-filter").trigger("click");
  }, 100);
});

$(document).on("click", "#map_page_geo_address_desk", function () {
  $("#map_page_geo_address_desk").val("");
});

$(document).on("keydown", "#map_page_geo_address_desk", function () {
  $("body").attr("data-isPlaceChanged", "false");
});

/* 
function globalinitMap_browse() {
  var idsearch = document.getElementById("googleidsearch").value;
  autocomplete = new google.maps.places.Autocomplete(
    document.getElementById("" + idsearch + ""),
    {
      componentRestrictions: countryRestrict,
    }
  );
  autocomplete.addListener("place_changed", fillInAddress_browse);
}
function fillInAddress_browse() {
  console.log("fillInAddress_browse....>");
  $("body").attr("data-isPlaceChanged", "true");
  var place = autocomplete.getPlace();
  var idsearch = "map_page_geo_address_desk";
  $("#lat").val(place.geometry.location.lat());
  $("#lng").val(place.geometry.location.lng());
  if (
    place.address_components !== undefined &&
    place.address_components.length > 0
  ) {
    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      if (componentForm[addressType]) {
        var val = place.address_components[i][componentForm[addressType]];
        if (addressType == "postal_code") {
          $("#map_page_geo_zipcode").val(val);
          $(".sortby-filter-4").trigger("click");
        }
      }
    }
  }
  setTimeout(function () {
    if ($("#job-location-form").length >= 1) {
      $("#job-location-form").submit();
    } else {
      var DeviceType = $("body").attr("data-DeviceType");
      if (DeviceType != "mobile") {
		  
		  console.log("111999999");
		  
        $(".search-data-filter").trigger("click");
      } else {
        currentpage = 1;
        $("#currentpage").val(currentpage);
		manage_url(currentpage); 
		
        filterMobile();
      }
    }
  }, 100);
} */

/***OSM ****/

function globalinitMap_browse() {
  var idsearch = $("#googleidsearch").val();
  if (!idsearch) return;
  initAutocomplete(idsearch, false);
}

function initAutocomplete(inputId, isGlobal = false) {
  var $input = $("#" + inputId);
  if (!$input.length) return;

  $input.off(".osm");
  $(".osm-autocomplete").remove();
  $input.parent().css("position", "relative");

  var $list = $("<ul class='osm-autocomplete'></ul>").css({
    position: "absolute",
    top: "100%",
    left: 0,
    zIndex: 9999,
    background: "#fff",
    border: "1px solid #ccc",
    width: $input.outerWidth(),
    maxHeight: "240px",
    overflowY: "auto",
    listStyle: "none",
    padding: 0,
    margin: 0,
  });

  $input.after($list);

  let timer;
  $input.on("input.osm", function () {
    clearTimeout(timer);
    var q = $input.val().trim();
    if (q.length < 3) {
      $list.hide();
      return;
    }

    timer = setTimeout(function () {
      $.getJSON(
        "/ajax/geocode",
        { q: q, global: isGlobal ? 1 : 0 },
        function (res) {
          $list.empty();
          if (!res.features || !res.features.length) {
            $list.hide();
            return;
          }

          res.features.forEach(function (feature) {
            var p = feature.properties || {};
            var label = [p.name, p.city, p.state, p.country]
              .filter(Boolean)
              .join(", ");

            $("<li>")
              .text(label)
              .css({ padding: "8px 10px", cursor: "pointer" })
              .on("click", function () {
                $input.val(label);
                $list.hide();
                fillInAddress_browse(feature, inputId);
              })
              .appendTo($list);
          });

          $list.show();
        },
      );
    }, 250);
  });

  $(document).on("click.osm", function (e) {
    if (!$(e.target).closest($input).length) $list.hide();
  });
}

function fillInAddress_browse(feature, inputId) {
  $("body").attr("data-isPlaceChanged", "true");

  var c = feature.geometry.coordinates;
  var p = feature.properties || {};

  console.log(p);

  $("#lat").val(c[1]);
  $("#lng").val(c[0]);

  if (p.postcode) {
    $("#map_page_geo_zipcode").val(p.postcode);
    $(".sortby-filter-4").trigger("click");
  }

  if (p.city) {
    $("#map_page_geo_city").val(p.city);
  }

  map_page_geo_city

  setTimeout(function () {
    var DeviceType = $("body").attr("data-DeviceType");
    if (DeviceType !== "mobile") {
      $(".search-data-filter").trigger("click");
    } else {
      $("#currentpage").val(1);
      manage_url(1);
      filterMobile();
    }
  }, 100);
}

/***OSM ****/

/*filter*/

function globalinitMap_browse_popup() {
  var idsearch = document.getElementById("googleidsearch").value;
  autocomplete = new google.maps.places.Autocomplete(
    document.getElementById("" + idsearch + ""),
    {
      componentRestrictions: countryRestrict,
    },
  );
  autocomplete.addListener("place_changed", fillInAddress_browse_popup);
}
function fillInAddress_browse_popup() {
  console.log("fillInAddress_browse_popup....");
  $("body").attr("data-isPlaceChanged", "true");
  var place = autocomplete.getPlace();
  var idsearch = "map_page_geo_address_desk";
  $("#lat").val(place.geometry.location.lat());
  $("#lng").val(place.geometry.location.lng());
  if (
    place.address_components !== undefined &&
    place.address_components.length > 0
  ) {
    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      if (componentForm[addressType]) {
        var val = place.address_components[i][componentForm[addressType]];
        if (addressType == "postal_code") {
          $("#map_page_geo_zipcode").val(val);
          $(".sortby-filter-4").trigger("click");
        }
      }
    }
  }
}
/*filter*/

$(document).on("click", ".search-data-filter", function () {
  if ($("body").attr("data-isPlaceChanged") == "false") {
    $("#map_page_geo_address_desk").val("");
  }
  var DeviceType = $("body").attr("data-DeviceType");
  var data_login = $("body").attr("data-login");
  if (DeviceType != "mobile") {
    var search_title = $("#search-title").val();
    var myRange = $("#myRange").val();
    if (myRange === undefined || myRange === null) {
      $("#myRange").val(250);
      var myRange = 250;
    }
    var map_address = $("#map_page_geo_address_desk").val();
    var map_zipcode = $("#map_page_geo_zipcode").val();
    var map_city = $("#map_page_geo_city").val();
    var lat = $("#lat").val();
    var lng = $("#lng").val();
    var map_address_Location = map_address;
    if (map_address_Location.length > 36) {
      map_address_Location = map_address_Location.substring(0, 34) + "...";
    }
    $("#valueLocation").html(map_address_Location);
    var filter_state = [];
    $("input:checkbox[name='state']:checked").each(function () {
      var vals = $(this).val();
      filter_state.push(vals);
    });
    var filter_jobtype = [];
    $("input:checkbox[name='jobtype']:checked").each(function () {
      var vals = $(this).val();
      filter_jobtype.push(vals);
    });

    var statusProfessional = $(
      "input:checkbox[name='statusProfessional']:checked",
    ).val();
    var statusSmallJob = $(
      "input:checkbox[name='statusSmallJob']:checked",
    ).val();
    if (
      statusProfessional === undefined ||
      statusProfessional === null ||
      statusProfessional == ""
    ) {
      statusProfessional = "";
    }
    if (
      statusSmallJob === undefined ||
      statusSmallJob === null ||
      statusSmallJob == ""
    ) {
      statusSmallJob = "";
    }

    var currentpage = $("#currentpage").val();

    console.log("click currentpage =", currentpage);

    if (
      currentpage === undefined ||
      currentpage === null ||
      currentpage == ""
    ) {
      currentpage = 1;
    }

    $("#currentpage").val(currentpage);
    manage_url(currentpage);

    var orderby = $("#orderbytext").attr("data-id");

    if (map_address != "") {
      $("#searchjobfilter").html(
        '<div class="col-4 d-flex"> <i class="fad fa-map-marker-alt" aria-hidden="true"></i>  <form class="job-location-form w-100"> <div class="form-group "> <label for="location">Din beliggenhet:</label> <input type="text" name="location" id="map_page_geo_address_desk"  class="map-page-geo-address-desk" placeholder="Skriv gate eller sted" value="' +
          map_address_Location +
          '"><i class="fa fa-times close action-close-map cursor-pointer" aria-hidden="true"  ></i> <input type="hidden" class="" id="map_page_geo_zipcode" placeholder="" value="' +
          map_zipcode +
          '" > <input type="hidden" class="" id="map_page_geo_city" placeholder="" value="' +
          map_city +
          '" > <input type="hidden" class="" id="lat" placeholder="" value="' +
          lat +
          '" > <input type="hidden" class="" id="lng" placeholder="" value="' +
          lng +
          '" > </div> </form> </div> <div class="col-8"> <div  class="d-flex"> <div class="job-location-info pr-4"> <h2>Juster avstand for søket</h2> <p><span attr-1="5" id="valueDistance">' +
          myRange +
          '</span> km luftlinje <strong id="valueLocation" class=" action-close-map cursor-pointer">Nullstill</strong></p> <div class="range"> <input type="range" min="1" max="500" value="' +
          myRange +
          '" class="slider"   id="myRange"> </div> </div> <form class="job-name-form" action="javascript:;" > <div class="form-group"> <label for="search-title">Søk i innhold</label> <input type="text" id="search-title" value="' +
          search_title +
          '" name="Search" placeholder="Søkeord" > <button type="button" class="search-btn search-data-filter-action-2 "><i class="fas fa-search" aria-hidden="true"></i></button> </div> <input type="hidden" class="search-data-filter "> </form> </div> </div> ',
      );
    } else {
      if (data_login == "login-yes") {
        var login_data =
          "<h2>Vi ser ikke hvor du er</h2> <p> Tast inn stedet du befinner<br> deg til høyre. </p>";
      } else {
        var login_data =
          '<h2>Vi ser ikke hvor du er</h2> <p> <a href="/innlogging">Logg inn</a> eller fortell oss hvor du befinner deg for å søke etter avstand. </p>';
      }

      $("#searchjobfilter").html(
        '<div class="col-4" ><i class="fad fa-map-marker-slash float-left"></i> ' +
          login_data +
          ' </div> <div class="col-8"> <div  class="d-flex pl-3"> <form class="job-location-form" id="job-location-form1" method="post"> <div class="form-group mr-3"> <label for="location">Din beliggenhet:</label> <input type="text" name="map_address" id="map_page_geo_address_desk"  class="map-page-geo-address-desk" placeholder="Skriv gate eller sted"> <input type="hidden" class="" id="map_page_geo_zipcode" name="map_zipcode" placeholder="" value="" ><input type="hidden" class="" id="map_page_geo_city" name="map_city" placeholder="" value=""> <input type="hidden" class="" id="lat" name="lat"  placeholder="" value="" > <input type="hidden" class="" id="lng" name="lng"  placeholder="" value="" > </div> </form>   <form class="job-name-form" action="javascript:;" > <div class="form-group"> <label for="search-title">Søk i innhold</label> <input type="text" id="search-title" name="Search" placeholder="Søkeord" value="' +
          search_title +
          '"> <button type="button" class="search-btn search-data-filter-action-2 "><i class="fas fa-search" aria-hidden="true"></i></button> </div>  <input type="hidden" class="search-data-filter "> </form> </div>  </div>',
      );
    }

    if (search_title == "") {
      $(".action-search-inputs-label-2 p").html("");
      $(".action-search-inputs-label-2").attr(
        "style",
        "display:none !important",
      );
    } else {
      $(".action-search-inputs-label-2 p").html(
        "&nbsp;" + search_title + "&nbsp;",
      );
      $(".action-search-inputs-label-2").attr("style", "");
    }
    var url = "/browse/filter";

    var meta_location = "";
    var controller = $("body").attr("data-controller");
    if (controller == "browsesmalljob") {
      var url = "/browsesmalljob/filter";
      var meta_location = $("#meta_location").val();
    }

    $.ajax({
      url: url,
      method: "POST",
      data: {
        search_title: search_title,
        filter_jobtype: filter_jobtype,
        filter_state: filter_state,
        myRange: myRange,
        map_address: map_address,
        map_zipcode: map_zipcode,
        map_city: map_city,
        lat: lat,
        lng: lng,
        statusProfessional: statusProfessional,
        statusSmallJob: statusSmallJob,
        orderby: orderby,
        currentpage: currentpage,
        DeviceType: DeviceType,
        meta_location: meta_location,
      },
      dataType: "text",
      success: function (script_response) {
        var data = $.parseJSON(script_response);

        if (data["success"] == "true") {
          manage_url_for_category_location(currentpage, data["location_slug"]);

          /**/
          /* if (map_address != "") {
            $(".tag-search-inputs-1").html("Finn oppdrag i hele Norge ("+data["job_count"]+")");
          }else{
            $(".tag-search-inputs-1").html("Finn oppdrag i hele Norge ("+data["job_count"]+")");
          } */

          var selectedCategories = $("input:checkbox[name='jobtype']:checked");
          if (selectedCategories.length > 0) {
            var parentBtnSel = selectedCategories.eq(0).attr("data-target3");
            var mainCategoryName = "";
            if (parentBtnSel) {
              mainCategoryName = $.trim($(parentBtnSel).text());
            }
            if (mainCategoryName) {
              $(".tag-search-inputs-1").html(
                "Finn oppdrag innen " +
                  mainCategoryName +
                  " (" +
                  data["job_count"] +
                  ")",
              );
            } else {
              $(".tag-search-inputs-1").html(
                "Finn oppdrag i hele Norge (" + data["job_count"] + ")",
              );
            }
          } else {
            $(".tag-search-inputs-1").html(
              "Finn oppdrag i hele Norge (" + data["job_count"] + ")",
            );
          }

          /**/

          $("#job_results").html(data["main_content"]);

          var tags = [];
          if ($("input[name='statusSmallJob']").is(":checked")) {
            tags.push("Småjobber");
          }
          if ($("input[name='statusProfessional']").is(":checked")) {
            tags.push("PRO-oppdrag");
          }
          if (map_address && $.trim(map_address) !== "") {
            tags.push(map_address);
          }
          if (map_address && $("#myRange").length) {
            var distVal = $("#myRange").val() || myRange;
            if (distVal && $.trim(distVal) !== "") {
              tags.push(distVal + " km");
            }
          }
          if (selectedCategories.length > 0) {
            var catNames = [];
            selectedCategories.each(function () {
              var lbl = $(this).next("label").text();
              if (lbl) {
                catNames.push($.trim(lbl));
              }
            });
            if (catNames.length > 0) {
              tags.push(catNames.join(", "));
            }
          }
          var summaryHtml = "";
          if (tags.length > 0) {
            var formatted = tags
              .map(function (t) {
                return $("<span>").text(t).prop("outerHTML");
              })
              .join(" | ");
            summaryHtml += "<div>Filtrert etter: " + formatted + "</div>";
          }
          summaryHtml +=
            '<div class="mt-2"><a href="javascript:;" id="reset_filters">Nullstill søk</a></div>';
          $("#filter_summary").html(summaryHtml);
          $(document)
            .off("click", "#reset_filters")
            .on("click", "#reset_filters", function () {
              /* $("input[name='statusSmallJob']").prop("checked", false);
              $("input[name='statusProfessional']").prop("checked", false); */
              $("input:checkbox[name='jobtype']").prop("checked", false);
              $("#search-title").val("");
              $(".search-data-filter").trigger("click");
            });
        }

        if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
          setTimeout(function () {
            $("html, body").animate(
              {
                scrollTop: localStorage.getItem(
                  "my_app_name_here-quote-scroll",
                ),
              },
              800,
            );
          }, 500);
        }
        $(document).one("keyup", ".map-page-geo-address-desk", function () {
          $("#googleidsearch").val(this.id);
          globalinitMap_browse();
        });
        $("#search-title").keydown(function (e) {
          if (e.keyCode == 13) {
            $(".search-data-filter").trigger("click");
          }
        });
        $("#map_page_geo_address_desk").keydown(function (e) {
          if (e.keyCode == 13) {
            console.log("115689");

            $(".search-data-filter").trigger("click");
          }
        });
      },
    });
  }
});

/*.sortby-filter-4*/

setTimeout(function () {
  var idd = $("input:checkbox[name='jobtype']:checked").val();
  if (idd !== undefined) {
    var id2 = $("#defaultCheck" + idd + "").attr("data-target2");
    var id3 = $("#defaultCheck" + idd + "").attr("data-target3");
    $("" + id2 + "").addClass("show");
  }
}, 100);

$(document).on("change", "#jobFrm  input[name='jobsubtype_id']", function () {
  var jobsubtype_id = $(this).val();

  var url = "/newjob/checkprofessional";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      jobsubtype_id: jobsubtype_id,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $(".input-forced-checked").prop("checked", true);
        $(".input-forced-checked").attr("readonly", "true");
      } else {
        $(".input-forced-checked").removeAttr("readonly");
      }
    },
  });
});

$(document).on(
  "change",
  "#jobFrm  input[name='proposals_wanted_option_professional']",
  function () {
    if ($(this).is("[readonly]")) {
      $(".input-forced-checked").prop("checked", true);
    }
  },
);

$(document).on("change", 'input[name="awardUser"]', function () {
  $(".awardUser-container").toggleClass("disabled");
  $(this).parent().parent().removeClass("disabled");
  $(this).parent().parent().toggleClass("selected");

  var nickname = $(this).attr("data-nickname");
  $(".action-awardUser span").html(nickname);

  var awardCheckboxes = $('input[name="awardUser"]').not(this);
  if (awardCheckboxes.prop("disabled") == false) {
    awardCheckboxes.prop("disabled", true);
  } else {
    awardCheckboxes.prop("disabled", false);
  }
  $("#awardUser-form .modal-footer .btn").toggleClass("d-none");
});

$(document).on("click", ".action-awardUser", function () {
  var user_id = $('input[name="awardUser"]:checked').val();
  var job_id = $("#job_id").val();
  var helper = "Y";

  if (typeof job_id == "undefined" || job_id == "") {
    var job_id = $(this).attr("job_id");
    type = 2;
  }

  if (typeof user_id != "undefined") {
    /**/

    var url = "/messages/cancelhireapproval_confirm";
    $(".action-awardUser").html("Vent..");
    console.log(user_id);
    console.log(job_id);
    console.log(helper);

    $.ajax({
      url: url,
      method: "POST",
      data: {
        user_id: user_id,
        job_id: job_id,
        helper: helper,
      },
      dataType: "text",
      success: function (script_response) {
        var data = $.parseJSON(script_response);
        $(".action-awardUser").html("Velg");
        if (data["success"] == "true") {
          $("#commonModal .modal-title").html(
            '<i class="fas fa-slash overlay" aria-hidden="true"></i><i class="fas fa-briefcase mr-3" aria-hidden="true"></i> Tusen takk',
          );
          $("#commonModal .modal-body").html(
            '<p class="m-4 text-center">Jobben er nå fjernet fra søk og du vil finne hjelperen din i chatten. Der vil du også finne hjelperens mobilnummer.</p>',
          );
          $("#commonModal .modal-footer").html(
            '<a   class="btn btn-primary px-4 " href="/myjobs">OK</a>',
          );

          notify_job_award(data["job_id"]);
        } else if (data["success"] == "false") {
          $("#commonModal .modal-body").html(
            "<div class='response-msg alert alert-danger'>" +
              data["message"] +
              "</div>",
          );
        } else {
          /* $(".selected-listing").trigger("click"); */
        }
      },
    });

    /**/
  }
});

/*message - remove helper*/

$(document).on("click", ".action-message-close-call", function () {
  $(".action-message-close-call").html("Vent..");

  var user_id = $(".selected-listing").attr("data-user_id");
  var job_id = $(".selected-listing").attr("data-job_id");
  var helper = $(".selected-listing").attr("data-helper");
  var help_id = $(".selected-listing").attr("data-help_id");

  var url = "/messages/remove_hired_helper_from_chat_1";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      user_id: user_id,
      job_id: job_id,
      helper: helper,
      help_id: help_id,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);

      $(".action-message-close-call").html(
        '<i class="fas fa-close"></i> Lukk samtale',
      );

      if (data["success"] == "true") {
        $("#commonModal").html(data["chat_content"]);
        $("#commonModal").modal("show");
      }
    },
  });
});

$(document).on("click", ".action-message-close-call-step-2", function () {
  $(".action-message-close-call-step-2").html("Vent..");

  var user_id = $(".selected-listing").attr("data-user_id");
  var job_id = $(".selected-listing").attr("data-job_id");
  var helper = $(".selected-listing").attr("data-helper");
  var help_id = $(".selected-listing").attr("data-help_id");

  var url = "/messages/remove_hired_helper_from_chat_2";
  $.ajax({
    url: url,
    method: "POST",
    data: {
      user_id: user_id,
      job_id: job_id,
      helper: helper,
      help_id: help_id,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        window.location.href = "/messages";
      }
    },
  });
});

$(document).on("click", ".action-message-close-call-confirm", function () {
  $(".action-message-close-call-confirm").html("Vent..");

  var user_id = $(".selected-listing").attr("data-user_id");
  var job_id = $(".selected-listing").attr("data-job_id");
  var helper = $(".selected-listing").attr("data-helper");
  var help_id = $(".selected-listing").attr("data-help_id");

  var url = "/messages/remove_hired_helper_from_chat_3";

  $.ajax({
    url: url,
    method: "POST",
    data: {
      user_id: user_id,
      job_id: job_id,
      helper: helper,
      help_id: help_id,
    },
    dataType: "text",
    success: function (script_response) {
      var data = $.parseJSON(script_response);
      if (data["success"] == "true") {
        $(".action-message-close-call-confirm").html("Klikk her");
        window.location.href = "/messages";
      }
    },
  });
});

/*message - remove helper*/

$(document).on("change", 'input[name = "location_status"]', function () {
  var val = $(this).val();
  if (val == 1) {
    $(".action-location-where").show();
    $(".action-location-to").show();
  } else {
    $(".action-location-where").hide();
    $(".action-location-to").hide();
  }
});

function manage_url(currentpage) {
  let newurl =
    window.location.protocol +
    "//" +
    window.location.host +
    window.location.pathname;
  if (currentpage != 1) {
    newurl += "?page=" + currentpage;
  }

  window.history.pushState({ path: newurl }, "", newurl);
}

function manage_url_for_category_location(currentpage, location_slug) {
  var current_path = window.location.pathname;
  var is_browse_page =
    current_path === "/finn" || current_path.indexOf("/finn/") === 0;

  if (is_browse_page) {
    var category_slug = null;

    // 1. Determine Category Slug
    var $checked_jobsubtypes = $("input:checkbox[name='jobtype']:checked");
    var selected_subtype_seos = [];
    $checked_jobsubtypes.each(function () {
      var seo = $(this).attr("data-seo");
      if (seo) {
        seo = $.trim(seo);
        if (seo && !selected_subtype_seos.includes(seo)) {
          selected_subtype_seos.push(seo);
        }
      }
    });

    /* if (selected_subtype_seos.length === 1) {
      category_slug = selected_subtype_seos[0];
    } else if ($checked_jobsubtypes.length === 1) {
      var only_subtype_seo = $checked_jobsubtypes.first().attr("data-seo");
      if (only_subtype_seo) {
        category_slug = only_subtype_seo;
      } else {
        var target = $checked_jobsubtypes.first().attr("data-target3");
        if (target) {
          var seo = $(target).attr("data-seo");
          if (seo) category_slug = seo;
        }
      }
    } else if ($checked_jobsubtypes.length > 1) {
      var selected_seos = [];
      $checked_jobsubtypes.each(function () {
        var target = $(this).attr("data-target3");
        if (target) {
          var seo = $(target).attr("data-seo");
          if (seo && !selected_seos.includes(seo)) selected_seos.push(seo);
        }
      });
      if (selected_seos.length === 1) {
        category_slug = selected_seos[0];
      }
    } */

     var selected_seos = [];
      $checked_jobsubtypes.each(function () {
        var target = $(this).attr("data-target3");
        if (target) {
          var seo = $(target).attr("data-seo");
          if (seo && !selected_seos.includes(seo)) selected_seos.push(seo);
        }
      });
      if (selected_seos.length === 1) {
        category_slug = selected_seos[0];
      }

    console.log(
      "manage_url_for_category_location category_slug =",
      category_slug,
    );
    console.log(
      "manage_url_for_category_location location_slug =",
      location_slug,
    );

    var new_path = "/finn";

    var hasCategory = category_slug && category_slug.trim() !== "";
    var hasLocation = location_slug && location_slug.trim() !== "";
    if (hasCategory || hasLocation) {
      new_path += "/oppdrag-og-smajobber-i";
    }

    if (category_slug) {
      new_path += "/" + category_slug;
    }
    if (location_slug) {
      new_path += "/" + location_slug;
    }

    console.log("manage_url_for_category_location new_path =", new_path);

    var final_url =
      window.location.protocol + "//" + window.location.host + new_path;
    if (currentpage != 1) {
      final_url += "?page=" + currentpage;
    }
    console.log("manage_url_for_category_location final_url =", final_url);

    window.history.pushState({ path: final_url }, "", final_url);
  }
}
