﻿var otpRequested = false;
baseUrl = $("#base-site-url").val();
function changeCaptch() {
    jQuery.ajax({
        type: "POST",
        url: baseUrl + "index.php/request/captcha_refresh",
        success: function (res) {
            if (res) {
                jQuery("div.image").html(res);
            }
        }
    });
}
function resetForm() {
	//shikha
    $("#complaintData #captcha").val("");
    $("#complaintData #complaintImage").val("");
	$('input[type=checkbox]').prop('checked', false);
    $("#complaintData textarea").val("");
    $("#complaintData select").val("0");
}
function validateEmail($email) {
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  return emailReg.test( $email );
}
function validateForm() {
    var validationFlag = false;
	var txtCustomerNameUpdate = document.getElementById("txtCustomerNameUpdate");
	//shikha
    var alpha = /^[a-zA-Z\s-, ]+$/; 
	if (!txtCustomerNameUpdate.value.match(alpha)) {
       toastr.error("Name Invalid. Please enter character only.");      
        return false;
   }
   else 
   {
    validationFlag =  true;
   }
     
   /*var txtCustomerMailUpdate = $('#txtCustomerMailUpdate').val();
   var filter =/^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i; 
	if (filter.test(txtCustomerMailUpdate)) {
         validationFlag =  true;
		 
   }
   else 
   {
	   toastr.error("Invalid email id.");      
        return false; 
		

   }*/
    if (validateMobileNumber('txtCustomerContactUpdate', 'Contact Number') && emptyFieldValidation('txtCustomerNameUpdate', 'Name')
        && emptyFieldValidation('txtComplaint', 'Complaint') && emptyFieldValidation('captcha', 'Captcha') 
        ) {
        validationFlag = true;
    } else {
        return false;
    }
  
    if (validationFlag && (!$("#departmentId").val() || $("#departmentId").val() == "")) {
        toastr.error("Please select the department for the complain.");
        $("#departmentId").css({ "border": "1px solid red" });
        return false;
    }       
    else {
        $("#departmentId").removeAttr('style');
        validationFlag = true;
    }
	if (validationFlag && (!$("#subjectId").val() || $("#subjectId").val() == "")) {
        toastr.error("Please select the subject for the complain.");
        $("#subjectId").css({ "border": "1px solid red" });
        return false;
    }       
    else {
        $("#subjectId").removeAttr('style');
        validationFlag = true;
    }
	if (validationFlag && (!$("#portalinfoId").val() || $("#portalinfoId").val() == "")) {
        toastr.error("Please select from where did you get the portal information?");
        $("#portalinfoId").css({ "border": "1px solid red" });
        return false;
    }       
    else {
        $("#portalinfoId").removeAttr('style');
        validationFlag = true;
    }
	if (validationFlag && $("#dnd").prop('checked') == false) {
        toastr.error("Please accept to allow us to call you for better experience");
        $("#dnd").css({ "border": "1px solid red" });
        return false;
    }       
    else {
        $("#dnd").removeAttr('style');
        validationFlag = true;
    }
    return validationFlag;

}
function addComplaint(element) {
    var result = validateForm();
    if (result) {
        //$("#Complaint_confirmation").dialog({ modal: true, dialogClass: "no-close", width: "500", height: "250", closeOnEscape: false });
        $.post(baseUrl + 'index.php/request/check_validation', { captcha: $("#captcha").val(), department: $("#departmentId").val() }, function (d) {
            if (d == 2) {
                toastr.error("Please select the department for the request.");
                $("#departmentId").css({ "border": "1px solid red" });
            } else {
                $("#departmentId").removeAttr('style');
                if (d == 1) {
                    changeCaptch();
					swal({ title: "Error!", text: "Captcha not match!", type: "error", timer: 2000, confirmButtonText: "Ok" });
                    //ShowDialog("Captcha not match", "Error", 300, 100);
                }
                else {
					$("#submitcomplain").attr("disabled", true);
                    $("#complaintData").submit();
					var progress = document.getElementById("progress");
					progress.style.width = "100%";
                }
            }
       
        });


    }
}
function verifyMobileNumber(element) {
    if (validateMobileNumber('txtCustomerContactUpdate', 'Contact Number')) {
        $(".wrongOTPMessage").hide();
        if (!otpRequested) {
            $.ajax({
                url: baseUrl + "index.php/request/sendOTP",
                type: 'post',
                data: { contactNo: $("#txtCustomerContactUpdate").val() },
                success: function (data) {

                    otpRequested = true;
					//shikha (Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape)
                    $(".otp-input-modal").modal({backdrop: 'static', keyboard: false}, 'show');
                    //$("#wardDetailsError").hide();
                    $("#step2").removeClass("disabled").addClass("active");
                    var progress = document.getElementById("progress");
					progress.style.width = "50%";
					disableResend();
					timer(60);

                },
                error: function () {
                    swal({ title: "Error!", text: "We are facing technical error!", type: "error", timer: 2000, confirmButtonText: "Ok" });
                    return false;
                }
            });

        }
        else {
			//shikha (Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape)
            $(".otp-input-modal").modal({backdrop: 'static', keyboard: false}, 'show');
        }
    }
}
function disableResend()
{
	$("#regenerateOTP").attr("disabled", true);

	timer(60);
	 //$('.regenerateOTP').prop('disabled', true);
  setTimeout(function() {
    // enable click after 1 second
	$('#regenerateOTP').removeAttr("disabled");
    //$('.disable-btn').prop('disabled', false);
  }, 60000); // 1 second delay
}
function timer(remaining) {
  let timerOn = true;
  var m = Math.floor(remaining / 60);
  var s = remaining % 60;
  
  m = m < 10 ? '0' + m : m;
  s = s < 10 ? '0' + s : s;
  document.getElementById('timer').innerHTML = m + ':' + s;
  remaining -= 1;
  
  if(remaining >= 0 && timerOn) {
    setTimeout(function() {
        timer(remaining);
    }, 1000);
    return;
  }

  if(!timerOn) {
    // Do validate stuff here
    return;
  }

}


$(document).ready(function () {
    baseUrl = $("#base-site-url").val();
    $("#txtCustomerContactUpdate").on("change", function () {
		$("#txtCustomerNameUpdate,#txtCustomerMailUpdate").removeProp("readonly");
        $("#complainant_id").val(0);
    });
	$("#departmentId").change(function(){
		var wardOptions='<option value="">Select ward</option>';
		if(department_wards[$(this).val()]>0){
			for(var counter=1;counter<=department_wards[$(this).val()];counter++){
				wardOptions+="<option value='"+counter+"'>W"+ counter +"</option>";
			}
		}else{
			wardOptions='<option value="">---No ward---</option>';
		}
		
		$('#wardNumber').empty().append(wardOptions);
	});
 
    $("#isAnonymous").change(function () {
        if ($(this).is(":checked")) {
            swal({
                title: "Are you sure? / क्या आपको यकीन है ?",
                text: "Are you sure you want to hide your identity? No one can see your contact information than Nodal team / क्या आप वाकई अपनी पहचान छिपाना चाहते हैं? नोडल टीम के अलावा कोई भी आपकी संपर्क जानकारी नहीं देख सकता है ",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, hide it please! / हां, कृपया इसे छुपाएं ! ",
                closeOnConfirm: true,
                closeOnCancel: true
            }, function (isConfirm) {
                if (isConfirm) {

                } else {
                    $('#isAnonymous').prop('checked', false);
                }
            });
        }
    });
    $('#regenerateOTP').on('click', function () {
		disableResend();
		timer(60);
        $.ajax({
            url: baseUrl + "index.php/request/sendOTP",
            type: 'post',
            data: { contactNo: $("#txtCustomerContactUpdate").val() },
            success: function (data) {
                swal({ title: "Sweet!", text: "One time password Message is sent again", timer: 2000, imageUrl: "../images/thumbs-up.jpg" });
            },
            error: function () {
                swal({ title: "Error!", text: "We are facing technical error!", type: "error", timer: 2000, confirmButtonText: "Ok" });
                return false;
            }
        });

    });
    $('#btnVerifyOtp').on('click', function () {
        $.ajax({
            url: baseUrl + "index.php/request/verifyOTP",
            type: 'post',
			dataType: 'json',
            data: { otp: $("#otp_input").val(), contactNo: $("#txtCustomerContactUpdate").val() },
            success: function (response) {
                if (response.VERIFIED == "SUCCESS") {
					if(response.COMPLAINANT_EXIST){
						$("#txtCustomerMailUpdate").val(response.data.email).prop("readonly", true);
						$("#txtCustomerNameUpdate").val(response.data.complainant_name).prop("readonly", true);
						$("#complainant_id").val(response.data.id);
						//shikha
						$("input[name=gender][value=" + response.data.gender + "]").prop('checked', true);
						$("input[name=divyang][value=" + response.data.divyang + "]").prop('checked', true);
					}
                    $(".otp-input-modal").modal("hide");
                    //$("#wardDetailsErrorSection,#wardDetailsSection").hide();
                    $("#txtCustomerContactUpdate").prop("readonly", "true");
                    $(".verifyButtonDiv").hide();
                    $(".otpVerifiedSection").show();
                    $("#step3").removeClass("disabled").addClass("active");
					var progress = document.getElementById("progress");
					progress.style.width = "75%";
                    //getComplainReport();
                } else if (response.ERROR == "INVALID_OTP") {
                    //alert("INvalid otp");
					swal({ title: "Error!", text: "The OTP you entered is invalid. / आपके द्वारा दर्ज OTP अमान्य है। ", type: "error"});
                    //$(".wrongOTPMessage").show();
                }
            },
            error: function () {
                swal({ title: "Error!", text: "We are facing technical error!", type: "error", timer: 2000, confirmButtonText: "Ok" });
            }
        });

    });

});
