//stabilizing  form
 
function sendFormFromTop(formdata){
    //$.postMessage({scrollTopformsubmit: true}, '*' );
    if($('#review_submit').length){
        $('#review_submit').trigger('click');
    }else{
        setTimeout(function(){  
            $(".swal-modal").css("vertical-align", "top");$(".swal-modal").css("margin-top", "18mm");
            $(".swal-button--confirm").css("background-color", "#f39834"); 
            $(".swal-footer").css("text-align", "center");
            $(".swal-button--confirm:not([disabled]):hover").css("background-color", "#f39834"); 
        }, 200);
        swal({
            title: "Are you sure?",
            text: "You are going to send the form to recipient(s)",
            icon: "warning",
            buttons: [
            'Cancel',
            'Ok'
            ],
            allowOutsideClick: false,
            closeOnClickOutside: false,
        }).then(function(isConfirm) {
        if (isConfirm) {
                $.postMessage({ formSendLoader: "true" }, '*');
                console.log(formdata);
                var formparams = {};
                var recipArray = [];
                var patidArray = [];
                if( formdata.staffFacing ==  'false'  || formdata.flowcheck ==  'practitioner' ){
                    if(formdata.AllowEdit && (formdata.AllowEdit == true || formdata.AllowEdit == 'true')){
                        $(".appnitro").submit();
                        var loader = document.getElementById('enrol-loader');
                        exit;
                    }
                    var res = formdata.recipientset.split(",");
                    for(var k=0;k<res.length;k++){
                        recipArray.push(res[k]);
                    }
                    var recipArraynew = [];
                    var tagreciparray = [];
                    var recipArraynew = $.grep(recipArray, function(value) {
                        if(value.indexOf('tag-') == 0){
                            tagreciparray.push(value.replace('tag-',''));
                        }
                        return value.indexOf('tag-') < 0;
                    });
                    formparams['form_id'] =  formdata.formids;
                    formparams['recipients'] = recipArraynew;
                    if( formdata.tagRecipients ==  'true' ){
                        formparams['tagRecipients'] = tagreciparray.toString();
                    }else{
                        formparams['tagRecipients'] = "";
                    }
                    formparams['message'] = '';
                    formparams['formSubmissionId'] = formdata.savedDraftid;
                    formparams['siteIds'] = $("#myavailablesitesids").val();
                    formparams['formSendMode'] = formdata.formSendMode;
                    formparams['applessMode'] =  formdata.applessMode;
                    formparams['staffFacing'] = formdata.staffFacing;
                    if(recipArray.length > 0 && formdata.recipientset != ""){
                        formparams['sendForm'] = 1;
                    }else{
                        formparams['sendForm'] = 0;
                    }
                        formparams['savedDraftID'] = formparams['formSubmissionId'];
                        formparams['message'] = formdata.messageadd;
                        formparams['bottombtn'] = 1;
                    if( formdata.flowcheck ==  'practitioner' ){
                        patidArray.push(formdata.patientId)
                        formparams['practitionerAssociatePatient'] = patidArray;
                        formparams['practitioner'] = 1;
                        formparams['orderChange'] = false;
                    }
                    localStorage.setItem('automaticDraft', 1);
                    localStorage.setItem('automatic', 1);
                    localStorage.setItem("notShowPopup", 1);
                    localStorage.removeItem('fileSaveDraftId');
                    $("#save_as_draft_submit_form").trigger('click',[formparams,'send']);
                
                
                }
            }
        });
    }
}

function send_form_recipients(data) {
    $.postMessage({ formSendLoader: "true" }, '*');
    const urlParams = new URLSearchParams(window.location.search);
    var fromMobile=urlParams.get('fromMob');
    var datasnew = JSON.stringify(data);
    datasnew = JSON.parse(datasnew);
    if (datasnew.sendForm == 1) {
        const ua = navigator.userAgent;
        var deviceType='desktop';
        if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
            deviceType="tablet";
        }else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
            deviceType="mobile";
        }
        if(deviceType!='desktop'){
            $(".submitLoaderMessage").text('Sending the Form. Please wait...');
            $(".callbell-loader").show();
        }
        localStorage.setItem('automaticDraft', 1);
        localStorage.setItem('automatic', 1);
        localStorage.setItem("notShowPopup", 1)
        if (datasnew.reviewchecking != true) {
            if (localStorage.getItem("fileSaveDraftId") == null) {
                $("#save_as_draft_submit_form").trigger('click');
                console.log("---------------------26");
            }
        }
        else {
            localStorage.setItem("fileSaveDraftId", localStorage.getItem("ptidsubmissionidNewstored"))
        }
        setTimeout(function () { finalSubmitnew(data); }, 300);
    }
}

function stripScripts(s) {
    var div = document.createElement('div');
    div.innerHTML = s;
    var scripts = div.getElementsByTagName('script');
    var i = scripts.length;
    while (i--) {
      scripts[i].parentNode.removeChild(scripts[i]);
    }
    return div.innerHTML;
  }
function onAjaxFail(errorFunction){
    errorFunction();

}
function deviceType() {
    const ua = navigator.userAgent;
    if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
        return "tablet";
    }
    else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
        return "mobile";
    }
    return "desktop";
};
function finalSubmitBottom(event) {
    
    $("#enrol-loader").removeClass('hide');
    var serverBaseUrl = baseurlLogged;
    var serverBaseUrlN = serverBaseUrl.replace("%3A%2F%2F", "://");
    var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
    var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
    var url = "";
  
    if (formpushmode == "sqs") {
      event.callbackURL = "";
      if (
        event.tagRecipients != "" &&
        event.recipients == "" &&
        event.staffFacing == "false"
      ) {
        event.formSendingSource = "Desktop-patient-UserTag";
      } else if (
        event.tagRecipients == "" &&
        event.recipients.length == "1"
      ) {
        if (event.staffFacing == "false") {
          event.formSendingSource = "Desktop-patient-SingleUser";
        } else if (event.staffFacing == "practitioner") {
          event.formSendingSource = "Desktop-practitioner-SingleUser";
        }
      } else if (
        event.tagRecipients != "" ||
        event.recipients.length > 0 ||
        event.recipients.length == "1"
      ) {
        event.formSendingSource = "Desktop-patient-MultipleUser";
        if (event.staffFacing == "false") {
          event.formSendingSource = "Desktop-patient-MultipleUser";
        } else if (event.staffFacing == "practitioner") {
          event.formSendingSource = "Desktop-practitioner-MultipleUser";
        }
      }
      if (event.staffFacing == "false") {
        event.formType = "Patient";
      } else if (event.staffFacing == "practitioner") {
        event.formType = "practitioner";
      }
      url = serverBaseUrlN + "/cometchat/citus-health/v4/send-form.php";
    } else {
      url = serverBaseUrlN + "/cometchat/citus-health/v4/send-form-to-recipients.php";
    }
    event.formSubmissionId = localStorage.getItem("fileSaveDraftId");
    event.savedDraftID = localStorage.getItem("fileSaveDraftId");
    if (localStorage.getItem("Formmessage_"+uniQueFormIdentity) != null && localStorage.getItem("Formmessage_"+uniQueFormIdentity) != "null") {
        event.message = localStorage.getItem('Formmessage_'+uniQueFormIdentity);
    }
    event.useragent  = deviceType();
    if (localStorage.getItem("formMode_"+uniQueFormIdentity) != null && localStorage.getItem("formMode_"+uniQueFormIdentity) != "null") {
        event.formSendMode = localStorage.getItem("formMode_"+uniQueFormIdentity);
    }
    if(typeof uniQueFormIdentity!=='undefined' && uniQueFormIdentity!==null){
        event.formUniqueId = uniQueFormIdentity;
    }
    event.curlUrl= url;
    var settings = {
        "async": false,
        "crossDomain": true,
        "url": 'CorsHttpRequestProxy.php' ,
        "method": "POST",
        "headers": {
            "content-type": "application/json",
            "Authentication-Token": decodeURIComponent(loggedAuthKey),
            "cache-control": "no-cache"
        },
        "processData": false,
        "data": JSON.stringify(event)
    }
    $.ajax(settings).done(function (response) {
        localStorage.setItem('automaticDraft', null);
        localStorage.setItem('automatic', null)
        localStorage.removeItem('notShowPopup');
        localStorage.removeItem('Formmessage_'+uniQueFormIdentity);
        localStorage.removeItem("formMode_"+uniQueFormIdentity);
        let useragent  = deviceType();
        if (useragent != "mobile") {
            if(typeof response!=='undefined' && response!==null && response){
                var responseStatus=JSON.parse(response).status;
                if(responseStatus==401){
                    window.parent.postMessage('{"fail":1}', "*");
                    $('#review_submit').prop('disabled', false);
					$('#review_back').prop('disabled', false);
				    $('.pagination-links').css("pointer-events",'auto');
                    $('input:hidden[name=submit_primary]:not([type=submit])').remove();
                    $("#send_button_value").remove();
                    $('#submit_secondary1').prop('disabled', false);
			        $('#submit_primary1').prop('disabled',false);
                    $('#submit_form1').prop('disabled',false);
                    $(".callbell-loader").hide();
                    $("#enrol-loader").addClass('hide');
                    return false;
                }
               } 
            if (formpushmode == "sqs") {
            	$.postMessage({ formSendLoaderRemove: "true" }, '*');
                window.parent.postMessage('{"status":1,"bottombtn":1}', "*");
				 $(".submitLoaderMessage").text('');
                 $(".callbell-loader").hide();
            }else{
                window.parent.postMessage(response, "*");
            }
            localStorage.setItem("sendrecpResult", response);
        }
        setTimeout(function () {
            $("#enrol-loader").addClass('hide');
            $(".appnitro").submit();
        }, 2000);
    }).fail(function (Response) {
        window.parent.postMessage('{"fail":1}', "*");
        $('#review_submit').prop('disabled', false);
        $('#review_back').prop('disabled', false);
        $('.pagination-links').css("pointer-events",'auto');
        $('input:hidden[name=submit_primary]:not([type=submit])').remove();
        $("#send_button_value").remove();
        $('#submit_secondary1').prop('disabled', false);
        $('#submit_primary1').prop('disabled',false);
        $('#submit_form1').prop('disabled',false);
        $(".callbell-loader").hide();
        $("#enrol-loader").addClass('hide');
       $.postMessage({ formSendLoaderRemove: "true" }, '*');
       $(".submitLoaderMessage").text('');
       $(".callbell-loader").hide();
        
    });

}

function finalSubmitnew(event) {
    if (localStorage.getItem("fileSaveDraftId") == null) {
        setTimeout(function () { finalSubmitnew(event) }, 1000);
    }
    else {
        var formsubmissionid = localStorage.getItem("fileSaveDraftId");
        var serverBaseUrl = baseurlLogged;
        var serverBaseUrlN = serverBaseUrl.replace("%3A%2F%2F", "://");
        var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
        var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
        var url = serverBaseUrlN + '/cometchat/citus-health/v4/validate-form-data-for-privacy.php';

        var patientfrom;
        var ftypes = event.staffFacing;
        var validate_form_id = event.form_id
        var validateformdata = $("#validateformdata").val();

        //(ftypes == false || ftypes == 'false') &&
         console.log('form sending...'+ftypes);
         var practitionerFlow=false;
         if (typeof event.practitionerAssociatePatient!='undefined' && typeof event.practitionerAssociatePatient[0]!='undefined' && event.practitionerAssociatePatient[0]>0) {
            practitionerFlow =true;
         }
        if (formsubmissionid && validate_form_id && validateformdata == 1 && (!practitionerFlow || ($("#practitionerHipaaValidation").length && $("#practitionerHipaaValidation").val()==1))) {
            let recipientset = event.recipients;
            let reclength = recipientset.length;
            if (reclength == 1) {
                var result_patient = recipientset[0].indexOf("--");
                if (result_patient == -1) {
                    patientfrom = recipientset[0];
                }
                else {
                    const mypatArray = recipientset[0].split("--");
                    patientfrom = mypatArray[1];
                }
                console.log("&&&&&&&&&&&&&&");
                console.log(event.practitionerAssociatePatient);
                console.log("ftype===="+ftypes);
                console.log("&&&&&&&&&&&&&&");

                if (typeof event.practitionerAssociatePatient!='undefined' && typeof event.practitionerAssociatePatient[0]!='undefined' && event.practitionerAssociatePatient[0]>0) {
                    patientfrom = event.practitionerAssociatePatient[0];
                }
                if (patientfrom) {
                    var dataprivacy = { "form_id": validate_form_id, "recipient_id": patientfrom, "staff_prefill_submission_id": formsubmissionid,"curlUrl": url};
                    var settings = {
                        "async": false,
                        "crossDomain": true,
                        "url": 'CorsHttpRequestProxy.php',
                        "method": "POST",
                        "headers": {
                            "content-type": "application/json",
                            "Authentication-Token": decodeURIComponent(loggedAuthKey),
                            "cache-control": "no-cache"
                        },
                        "processData": false,
                        "data": JSON.stringify(dataprivacy)
                    }
                    $.ajax(settings).done(function (resultnew) {
                        resultnew =JSON.parse(resultnew);
                        var msgtxt_hippa;
                        msgtxt_hippa = "<p class='newalerthipaap'>We noticed the changes to the following Form Fields when compared to the pre populated values. Please review & confirm these changes are correct. Patient may get wrong information. If the information is correct, then click on Continue to send the Form. If the information is wrong, click on Cancel to go back to the Form and correct the information and Send again </p> <br/>";
                        var mis_msgtxt = "<table class='newalerthipaa'><tr><th>Field Name</th><th>Current/Changed Value</th><th>Original Value</th></tr>";
                        if (resultnew['status']["statusMessage"] == 'Success' && resultnew['status']["formFieldDataMatched"] == "false") {
                            if (resultnew['formFieldNotMatched']) {
                                $(jQuery.parseJSON(JSON.stringify(resultnew['formFieldNotMatched']))).each(function () {
                                    mis_msgtxt += "<tr><td>" + this.element_name + "</td><td>" + this.element_current_value + "</td><td>" + this.element_actual_value + "</td></tr>";
                                });
                            }
                            mis_msgtxt += "</table>";
                            msgtxt_hippa += mis_msgtxt;
                            setTimeout(function () {
                                $(".swal-modal").css("vertical-align", "top");
                                $(".swal-overlay").css("height", $("#form_container").height()); 
                                $(".swal-overlay").css("overflow-y", "auto"); 
                                $(".swal-modal").css("margin-top", "18mm");
                                $(".myclass").css("background-color", "#f39834");
                                $(".swal-footer").css("text-align", "center");
                                $(".swal-button--confirm:not([disabled]):hover").css("background-color", "#f39834");
                            }, 200);
                            $("html,body").scrollTop(0);
                            var spans = document.createElement("span");
                            spans.innerHTML = msgtxt_hippa;
                            $.postMessage({ formSendLoaderRemove: "true" }, '*');
                            $(".submitLoaderMessage").text('');
                            $(".callbell-loader").hide();
                            swal({
                                html: true,
                                title: "HIPAA ALERT",
                                content: spans,
                                icon: "error",
                                type: "error",
                                buttonsStyling: false,
                                buttons:
                                {
                                    confirm:
                                    {
                                        text: "Continue",
                                        visible: true,
                                        className: "swal-button--cancel ",
                                        closeModal: true,
                                    }
                                    , cancel:
                                    {
                                        text: "Cancel",
                                        visible: true,
                                        className: "swal-button--cancel myclass",
                                        closeModal: true,
                                    }
                                }
                            }).then(function (isConfirm) {
                                const urlParams = new URLSearchParams(window.location.search);
                                var loggedUsers_id = urlParams.get('toId') ? urlParams.get('toId') : '';
                                if (isConfirm) {
                                    $.postMessage({ formSendLoader: "true" }, '*');
                                    const ua = navigator.userAgent;
                                    var deviceType='desktop';
                                    if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
                                        deviceType="tablet";
                                    }else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
                                        deviceType="mobile";
                                    }
                                    if(deviceType!='desktop'){
                                        $(".submitLoaderMessage").text('Sending the Form. Please wait...');
                                        $(".callbell-loader").show();
                                    }
                                    var data = { 
                                        activityName:"Continue hipaa alert on form sent",
                                        activityType: "Continue hipaa alert on form sent",  
                                        activityDescription:loggedUsers_id +" Continue HIPAA alert on form sent for the form "+ validate_form_id +" - patient - "+patientfrom, 
                                        createdBy:loggedUsers_id,
                                        curlUrl:serverBaseUrlN + "/cometchat/citus-health/v4/track-activity.php"
                                        
                                        };
                                    var settings = {
                                        "async": true,
                                        "crossDomain": true,
                                        "url":'CorsHttpRequestProxy.php',
                                        "method": "POST",
                                        "headers": {
                                            "cache-control": "no-cache",
                                            "Access-Control-Allow-Origin": '*',
                                            "authentication-token": decodeURIComponent(loggedAuthKey)
                                        },
                                        "data": data
                                    }
                                    $.ajax(settings);
                                    finalSubmitBottom(event);
                                }
                                else {
                                    
                                    var data = { 
                                        activityName:"Cancelled hipaa alert on form sent",
                                        activityType: "Cancelled hipaa alert on form sent",  
                                        activityDescription:loggedUsers_id +" Cancelled HIPAA alert on form sent for the form "+ validate_form_id +" - patient - "+patientfrom, 
                                        createdBy:loggedUsers_id,
                                        curlUrl:serverBaseUrlN + "/cometchat/citus-health/v4/track-activity.php"
                                        
                                        };
                                    var settings = {
                                        "async": true,
                                        "crossDomain": true,
                                        "url": 'CorsHttpRequestProxy.php',
                                        "method": "POST",
                                        "headers": {
                                            "cache-control": "no-cache",
                                            "Access-Control-Allow-Origin": '*',
                                            "authentication-token": decodeURIComponent(loggedAuthKey)
                                        },
                                        "data": data
                                    }
                                    $.ajax(settings);
                                    $('input:hidden[name=submit_primary]:not([type=submit])').remove();
                                    $("#send_button_value").remove();
                                    $('#submit_secondary1').prop('disabled', false);
                                    $('.pagination-links').css("pointer-events",'auto');
                                    if($('#submit_primary1').length) $('#submit_primary1').prop('disabled',false);
                                    if($('#submit_form1').length) $('#submit_form1').prop('disabled',false);
                                    if($('#review_submit').length) $('#review_submit').prop('disabled',false);
                                    if($('#review_back').length) $('#review_back').prop('disabled',false);
                                    $('input:hidden[name=review_submit]:not([type=submit])').remove();
                                    localStorage.removeItem('notShowPopup');
                                }
                            });
                        }
                        else {
                            finalSubmitBottom(event);
                        }
                    });
                }
                else {
                    finalSubmitBottom(event);
                }
            }
            else {
                finalSubmitBottom(event);
            }
        }
        else {
            finalSubmitBottom(event);
        }
    }
}



var draftFail = 0;
var initialDraft = 0
$(document).on('click', '#submit_primary1', function (event, res) {
    event.preventDefault();
    $(this).prop('disabled', true);
    $('#submit_secondary1').prop('disabled', true);
    $('.pagination-links').css("pointer-events",'none');
    if($(this).val()=='Send') $(this).prop('disabled',false);
    localStorage.setItem('automatic', 1);
    localStorage.setItem("automaticDraft", 1);
    if ((window.location.href.indexOf("/view.php") > -1) || (loadformType == 'worklist')) {
            $("#submit_primary").trigger('click');
    } else {
        if (AllowEdit == 'true' || AllowEdit == true) {
            $("#save_as_draft_allow_edit").trigger('click', [1, 'primary']);
        } else {
            $("#save_as_draft_submit_form").trigger('click', [1, 'primary']);
        }
        if($(".pagination-links").length){
            var activeId= $(".ap_tp_text_active").attr('id');
            if(activeId){
                var activePageNumber = activeId.split("_")[2];
                if(activePageNumber==$(".pagination-links").length){
                    $('<div class="loaderImg" style="position: fixed;overflow: auto;top: 0;bottom: 0;right: 0;background-color:rgba(0, 0, 0, 0.5);left: 0;height:auto;padding-top: 11%;text-align: center;"></div><div class="loader-image-div" style="text-align: center;"><img src="images/loaderspin.gif" style="width: 98px;position: relative;"><span style="color:white;z-index: 9999999999;position: relative;"> Please wait, your Form is being saved…</span></div>').insertBefore($(this));
                    
                }

            }
        }
    }
})
$(document).on('click', '#submit_secondary1', function (event) {
    event.preventDefault();
    localStorage.setItem('automatic', 1);
    localStorage.setItem("automaticDraft", 1);
    if ((window.location.href.indexOf("/view.php") > -1) || (loadformType == 'worklist')) {
           $("#submit_secondary").trigger('click');
    } else {
        if (AllowEdit == 'true' || AllowEdit == true) {
            $("#save_as_draft_allow_edit").trigger('click', [1, 'secondary']);
        } else {
            $("#save_as_draft_submit_form").trigger('click', [1, 'secondary']);
        }
    }
})
$(document).on('click', '#submit_form1', function (event) {
    event.preventDefault();
    if($(this).val()=='Send') $(this).prop('disabled',true);
    console.log(loadformType+"loadformType");
    var clientId=0;
    function getUrlVars()
    {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
    }
    if (getUrlVars()["clientId"]) {
        clientId =getUrlVars()["clientId"];
    }else if (getUrlVars()["tenantId"]) {
        clientId =getUrlVars()["tenantId"];
    }
    console.log(clientId+"clientId");
    
    if ((window.location.href.indexOf("/view.php") > -1) || (loadformType == 'worklist')) {
        console.log(clientId+'clientId22'+loadformType+'loadformType'); 
        $("#submit_form").trigger('click');
    }else{
        if(loadformType != 'worklist'){
            event.preventDefault();
            var serverBaseUrl = baseurlLogged;
            if(serverBaseUrl&& serverBaseUrl!== 'undefined'&& serverBaseUrl!== 'null'&& serverBaseUrl!== null ){
            var serverBaseUrlN = serverBaseUrl.replace("%3A%2F%2F", "://");
            var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
            var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
            const urlParams = new URLSearchParams(window.location.search);
            var loggedUsers_id = urlParams.get('toId') ? urlParams.get('toId') : '';
            var forms_id =urlParams.get('formId');
            var formName =decodeURIComponent(urlParams.get('formName')); 
            if (typeof urlParams.get('sentId') !== 'undefined' && urlParams.get('sentId') !== null && urlParams.get('sentId') != 'null' && typeof urlParams.get('loginUserId') !== 'undefined' && urlParams.get('loginUserId') !== null) {
                loggedUsers_id = urlParams.get('loginUserId');

            }
            if (typeof urlParams.get('FormEntryID') !== 'undefined' && urlParams.get('FormEntryID') !== null && urlParams.get('FormEntryID') != 'null' && typeof urlParams.get('loginUserId') !== 'undefined' && urlParams.get('loginUserId') !== null) {
                loggedUsers_id = urlParams.get('loginUserId');
            }
            var datas = {activityName:"Form Submission",activityType:"Form Submission",activityDescription:loggedUsers_id +" Form Submission for the form -"+ formName +"(Form Id:" + forms_id+")", 
                createdBy:loggedUsers_id,curlUrl:serverBaseUrlN + "/cometchat/citus-health/v4/track-activity.php"
                
                };
            var settings = {
                "async": true,
                "crossDomain": true,
                "url":'CorsHttpRequestProxy.php',
                "method": "POST",
                "headers": {
                    "cache-control": "no-cache",
                    "Access-Control-Allow-Origin": '*',
                    "authentication-token": decodeURIComponent(loggedAuthKey)
                },
                "data": datas
            }
            $.ajax(settings);
            localStorage.setItem('automatic', 1);
            localStorage.setItem("automaticDraft", 1);
            }
            else{
                $("#submit_form").trigger('click');
            }
        }
    }
    
    if ((window.location.href.indexOf("/view.php") > -1) || (loadformType == 'worklist' && clientId ==0)) {
         console.log(clientId+'clientId11'+loadformType+'loadformType');  
        $("#submit_form").trigger('click');
    } else {
        if (AllowEdit == 'true' || AllowEdit == true) {
            $("#submit_form").trigger('click');
        } else {
            if(loadformType != 'worklist'){
                if($("#reviewStauts").val()!=1){
                    
                    $('<div class="loaderImg" style="position: fixed;overflow: auto;top: 0;bottom: 0;right: 0;background-color:rgba(0, 0, 0, 0.5);left: 0;height:auto;padding-top: 11%;text-align: center;"></div><div class="loader-image-div" style="text-align: center;"><img src="images/loaderspin.gif" style="width: 98px;position: relative;"><span style="color:white;z-index: 9999999999;position: relative;"> Please wait, your Form is being saved…</span></div>').insertBefore($(this));
                            
                }
                $("#save_as_draft_submit_form").trigger('click', [1, 'submit_form']);
            }
           
        }

    }

})


$(document).on('keypress', '#form_container input', function (e) {
//$('#form_container').keypress(function (e) {
    var key = e.which;    
    if(key == 13)  // the enter key code
     {  
          e.preventDefault();
          $('#submit_primary1').trigger('click'); 
     }
});


const checkConnection = () => fetch('https://assets.citushealth.com/a/0/img/account-logo-on-white-bg.png?ver=' + Date.now())
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP status ' + response.status);
        }
        return response;
    })
    .then(response => 'online')
    .catch(error => 'offline');

var bStaffChangeValidation = false;
var globalJsonData;
var loggedTenant_id;
var loggedUser_id;
var baseurlLogged;
var loggedAuthKey;
var requiredArray = [];
var AllowEdit;
var loadformType;
var entryId;
var uniQueFormIdentity;
/*** myrx integration end ***/
var patientUserid;
/*** myrx integration end ***/
var formpushmode;
// enter key press search
function handle(e, i) {
    if (e.keyCode === 13) {
        e.preventDefault();
        $("#new_added_elements_search-" + i).trigger('click');

    }
}
// Check if there any input present in the inpu field
$(document).on('keyup mouseout mouseover focusin', '.dynamicContent :input', function () {
    $(".dynamicContent").find("li").each(function (index) {
        if (($.trim(($("#" + $(this).attr('id')).find('input').val())).length > 0) || ($.trim(($("#" + $(this).attr('id')).find('.textarea').val())).length > 0)) {
            $(".dynamicFooter .btn_save").removeAttr('disabled', true);
            return false;
        } else {
            $(".dynamicFooter .btn_save").attr('disabled', true);
        }
    });
});


// plus button click 
function createNewMasterData(index, cssClass) {
    let searchKeyword = $("#SearchInput-" + index).val();
    $("#searchKeyword").val(searchKeyword);
    $("#indexvalue").val(index);
    $('.dynamicContent').html("");
    var elems = document.querySelectorAll("[class*=" + cssClass + "]");
    var clonedContainer;

    let notpermittedClasses = ['checkboxes', 'multiple_choice', 'dropdown', 'simple_name', 'address', 'matrix', 'section_break', 'page_break', 'media'];
    for (var i = 0; i < elems.length; i++) {
        clonedContainer = elems[i].cloneNode(true);
        if (!(notpermittedClasses.some(className => elems[i].classList.contains(className)))) {
            $('.dynamicContent').append(clonedContainer);
            $('.dynamicContent li').find('.uploadifive-button').closest("li").remove()
            $('.dynamicContent li').find('.mf_sigpad_clear').closest("li").remove()
            $(".dynamicContent").find('.date_field').children('fieldset').find('span').find('input').addClass('numberonly');
            $(".dynamicContent").find('.time_field').children('fieldset').find('span').find('input').addClass('numberonly');
            $(".dynamicContent").find('.phone').children('fieldset').find('span').find('input').addClass('numberonly');
            $(".dynamicContent").find('.price').find('.main_currency').find('input').addClass('numberonly');
            $(".dynamicContent").find('.price').find('.sub_currency').find('input').addClass('numberonly');

        }
    }


    var selectbox = "";
    var available_sites = $("#myavailablesites").val();
    if (available_sites != "") {
        var obj = jQuery.parseJSON(available_sites);

        if ($("#multisite_enable_check").val() == 1) {
            selectbox += '<select id="sites-select" multiple placeholder="Please choose Site(s)">';
            $.each(obj, function (key, value) {
                selectbox += '<option value=' + value.id + '>' + value.name + '</option>';
            });
            selectbox += '</select>';
            $('.dynamicContent').prepend('<div class="dropclass"><label class="description" id="siteselection">Site(s):</label>' + selectbox + '</div><div class="chkclass"><input id="chkall" type="checkbox"><label class="selectall" for="chkall">Select All</label></div>');

            $('#sites-select').select2();
        } else {
            selectbox += '<input type="hidden" id="sites-select" value="' + obj[0].id + '">';
            $('.dynamicContent').prepend(selectbox);
        }


    }


    $(".dynamicContent").find('.time_field').children('fieldset').find('span').addClass('timespan');
    $(".description").removeClass('timespan');
    $("#btn_save").attr('onclick', "saveFieldDatas(" + index + ")");
    $(".dynamicContent ." + cssClass).find('div:eq(0)').show();
    $(".dynamicContent .new_added_elements-" + index).remove();
    $(".dynamicContent #displaySearch-" + index).remove();
    $("#popTitle").html("Please fill out the form below");
    window.parent.postMessage('popopen', "*");

    // call mutation createMasterDataDetails
    createMasterDataDetails(cssClass);
}

$(document).on('keypress', '.dynamicContent .numberonly', function (e) {
    var charCode = (e.which) ? e.which : e.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
});

// searching master data 
function searchMasterData(index, cssClass, types) {
    var SearchInput;
    var myavailablesitesids = $("#myavailablesitesids").val();
    if (types == 'typesearch') {
        SearchInput = $("#SearchInput-" + index).val();
    } else {
        SearchInput = types;
    }
    var serverBaseUrlN = baseurlLogged.replace("%3A%2F%2F", "://");
    serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
    serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
    var url = serverBaseUrlN + '/cometchat/citus-health/forms-masterdata-wrapper.php';

    var datas = JSON.stringify({ "tenantId": loggedTenant_id, "searchText": SearchInput, "cssClass": cssClass, "siteIds": myavailablesitesids,"curlUrl":url });
    $.ajax({
        type: 'POST',
        url: 'CorsHttpRequestProxy.php',
        dataType: 'json',
        data: datas,
        headers: {
            "cache-control": "no-cache",
            "Access-Control-Allow-Origin": '*',
            "authentication-token": decodeURIComponent(loggedAuthKey)
        },
        success: function (data) {
            //data=JSON.parse(data);
            if (types == 'typesearch') {
                $("#displaySearch-" + index).show();
                var jsonData = data
                globalJsonData = jsonData['masterData'];
                var cnt = jsonData['masterData'].length;
                var str = "";
                if (cnt > 0) {
                    str += '<ul>';
                    for (var i = 0; i < cnt; i++) {
                        var names = jsonData["masterData"][i].name;
                        var names1 = escape(names);

                        var cssClassnew = "'" + cssClass + "'";
                        str += '<li onclick="prepopulateData(' + index + ',' + jsonData["masterData"][i].id + ',';
                        str += "`" + names1 + "`";
                        str += ',' + cssClassnew + ')">' + jsonData["masterData"][i].name + '</li>';
                    }
                    str += '</ul>';
                } else {
                    str = "No Matching Data Found";
                }
                $("#displaySearch-" + index).html(str);
                $("#types").val(0)
            } else {
                var jsonData = data
                globalJsonData = jsonData['masterData'];
                $("#types").val(1)
            }
        }
    });
}

// Reset button click
function clearFilter(index, cssClass) {
    $("#SearchInput-" + index).val("");
    $("#displaySearch-" + index).hide();
    $('[class*="' + cssClass + '"]').find('input').val('')
    $('[class*="' + cssClass + '"]').find('.textarea').val('')
}

$(function () {

    //mobile app message change


    setTimeout(function () {

        if ($(".message-save-as-draft").length) {
            if (localStorage.getItem(localStorage.getItem('myUniqueKey') + '_message') != null && localStorage.getItem(localStorage.getItem('myUniqueKey') + '_message') != undefined) {
                saveAsDraftMessage();
            }
        }


    }, 1200);


    //mobile app message change

    // form stabilization
    window.onmessage = function (event) {

        var datasnew = JSON.stringify(event.data);
        datasnew = JSON.parse(datasnew);
        if(typeof datasnew.completedFormRecipientsPost !== 'undefined'){// check post message exist key called completedFormRecipientsPost
            if(!$("#completed-forms-recipients").length) {
                $("#li_buttons").append('<input type="hidden" id="completed-forms-recipients" value="' + datasnew.completedFormRecipientsPost +' " name="completed-forms-recipients" />');
            } else {
                document.getElementById("completed-forms-recipients").value = datasnew.completedFormRecipientsPost;
            }
        } else {
            localStorage.setItem('Formmessage_'+uniQueFormIdentity, null);
            localStorage.setItem("formMode_"+uniQueFormIdentity, null);
            if (datasnew.sendviaPostmessage == 1) {
                localStorage.setItem('Formmessage_'+uniQueFormIdentity, datasnew.messagewithform);
                localStorage.setItem("formMode_"+uniQueFormIdentity, datasnew.formsendingmode);
            }
            if (datasnew.sendForm == 1 && datasnew.sendfromtop != 0) {
                localStorage.setItem('automaticDraft', 1);
                localStorage.setItem('automatic', 1);
                localStorage.setItem("notShowPopup", 1);
                localStorage.removeItem('fileSaveDraftId');
                $("#save_as_draft_submit_form").trigger('click',[event,'send']);
            }
        }
    };

    function finalSubmitTop(sendEvent) {
        event  = {};
        event.data = {};
        Object.assign(event.data, sendEvent);
        console.log(event);
        console.log("====================event=====================finalsubmittop==============");    
        var serverBaseUrl = getQueryString().serverBaseUrl;
        var serverBaseUrlN = serverBaseUrl.replace("%3A%2F%2F", "://");
        var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
        var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
        var url = "";
        if (formpushmode == "sqs") {
            event.data.callbackURL = "";
            if (localStorage.getItem("Formmessage_"+uniQueFormIdentity) != null && localStorage.getItem("Formmessage_"+uniQueFormIdentity) != "null") {
                event.data.message = localStorage.getItem('Formmessage_'+uniQueFormIdentity);
            }
            event.useragent  = deviceType();
            if (localStorage.getItem("formMode_"+uniQueFormIdentity) != null && localStorage.getItem("formMode_"+uniQueFormIdentity) != "null") {
                event.data.formSendMode = localStorage.getItem("formMode_"+uniQueFormIdentity);
            }
            if (
              event.data.tagRecipients != "" &&
              event.data.recipients == "" &&
              event.data.staffFacing == "false"
            ) {
              event.data.formSendingSource = "Desktop-patient-UserTag";
            } else if (
              event.data.tagRecipients == "" &&
              event.data.recipients.length == "1"
            ) {
              if (event.data.staffFacing == "false") {
                event.data.formSendingSource = "Desktop-patient-SingleUser";
              } else if (event.data.staffFacing == "practitioner") {
                event.data.formSendingSource = "Desktop-practitioner-SingleUser";
              }
            } else if (
              event.data.tagRecipients != "" ||
              event.data.recipients.length > 0 ||
              event.data.recipients.length == "1"
            ) {
              event.data.formSendingSource = "Desktop-patient-MultipleUser";
              if (event.data.staffFacing == "false") {
                event.data.formSendingSource = "Desktop-patient-MultipleUser";
              } else if (event.data.staffFacing == "practitioner") {
                event.data.formSendingSource = "Desktop-practitioner-MultipleUser";
              }
            }
            if (event.data.staffFacing == "false") {
              event.data.formType = "Patient";
            } else if (event.data.staffFacing == "practitioner") {
              event.data.formType = "practitioner";
            }
            url = serverBaseUrlN + "/cometchat/citus-health/v4/send-form.php";
          } else {
         url = serverBaseUrlN + '/cometchat/citus-health/v4/send-form-to-recipients.php';
          }
        event.data.formSubmissionId = localStorage.getItem("fileSaveDraftId");
        event.data.savedDraftID = localStorage.getItem("fileSaveDraftId");
        if(typeof uniQueFormIdentity!=='undefined' && uniQueFormIdentity!==null){
            event.data.formUniqueId = uniQueFormIdentity;
        }
        event.data.curlUrl=url;
        
        var settings = {
            "async": true,
            "crossDomain": true,
            "url": 'CorsHttpRequestProxy.php',
            "method": "POST",
            "headers": {
                "content-type": "application/json",
                "Authentication-Token": decodeURIComponent(loggedAuthKey),
                "cache-control": "no-cache"
            },
            "processData": false,
            "data": JSON.stringify(event.data)
        }
        $.ajax(settings).done(function (response) {




            localStorage.setItem('automaticDraft', null);
            localStorage.setItem('automatic', null)
            localStorage.removeItem('notShowPopup');
            localStorage.removeItem('Formmessage_'+uniQueFormIdentity);
            localStorage.removeItem("formMode_"+uniQueFormIdentity);
            if(typeof response!=='undefined' && response!==null && response){
                var responseStatus=JSON.parse(response).status;
                if(responseStatus==401){
                    window.parent.postMessage('{"fail":1}', "*");
                    $('#review_submit').prop('disabled', false);
					$('#review_back').prop('disabled', false);
				    $('.pagination-links').css("pointer-events",'auto');
                    $('input:hidden[name=submit_primary]:not([type=submit])').remove();
                    $("#send_button_value").remove();
                    $('#submit_secondary1').prop('disabled', false);
			        $('#submit_primary1').prop('disabled',false);
                    $('#submit_form1').prop('disabled',false);
                    $(".callbell-loader").hide();
                    $("#enrol-loader").addClass('hide');
                    return false;
                }
               } 
            if (formpushmode == "sqs") {
                window.parent.postMessage('{"status":1}', "*");
                window.parent.postMessage('{"status":1,"bottombtn":1}', "*");
                $.postMessage({ formSendLoaderRemove: "true" }, '*');
                $(".submitLoaderMessage").text('');
                $(".callbell-loader").hide();
            }else{
                window.parent.postMessage(response, "*");
            }
        }).fail(function (Response){
            window.parent.postMessage('{"fail":1}', "*");
            $('#review_submit').prop('disabled', false);
            $('#review_back').prop('disabled', false);
            $('.pagination-links').css("pointer-events",'auto');
            $('input:hidden[name=submit_primary]:not([type=submit])').remove();
            $("#send_button_value").remove();
            $('#submit_secondary1').prop('disabled', false);
            $('#submit_primary1').prop('disabled',false);
            $('#submit_form1').prop('disabled',false);
            $(".callbell-loader").hide();
            $("#enrol-loader").addClass('hide');
            $.postMessage({ formSendLoaderRemove: "true" }, '*');
            $(".submitLoaderMessage").text('');
            $(".callbell-loader").hide();
        });


    }
    function finalSubmit(event) {

        if (localStorage.getItem("fileSaveDraftId") == null) {
            localStorage.setItem("fileSaveDraftId",localStorage.getItem("ptidsubmissionidNewstored"));
            setTimeout(function () { finalSubmit(event); }, 2000);

        } else {
            console.log("form sending..2");
            var serverBaseUrl = getQueryString().serverBaseUrl;
            var serverBaseUrlN = serverBaseUrl.replace("%3A%2F%2F", "://");
            var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
            var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
            var url = serverBaseUrlN + '/cometchat/citus-health/v4/validate-form-data-for-privacy.php';
            var patientfrom;
            var formsubmissionid = localStorage.getItem("fileSaveDraftId");
            
            var validate_form_id = (event.data && event.data.form_id ) ? event.data.form_id :  event.form_id ;
            var ftypes = (event.data && event.data.staffFacing ) ? event.data.staffFacing :  event.staffFacing ;   
            var validateformdata = $("#validateformdata").val();
            //(ftypes == false || ftypes == 'false') &&
            
            (event.data && event.data.callbackURL ) ? event.data.callbackURL :  event.callbackURL ;  
            if (formsubmissionid && validate_form_id && validateformdata == '1' && (ftypes!= "practitioner" || ($("#practitionerHipaaValidation").length && $("#practitionerHipaaValidation").val()==1))) {
                let recipientset = (event.data && event.data.recipients ) ? event.data.recipients :  event.recipients ;
                let reclength = recipientset.length;
                let tagRecipients = (event.data && event.data.tagRecipients ) ? event.data.tagRecipients :  event.tagRecipients;
                if (reclength == 1 && tagRecipients == "") {
                    var result_patient = recipientset[0].indexOf("--");
                    if (result_patient == -1) {
                        patientfrom = recipientset[0];
                    }
                    else {
                        const mypatArray = recipientset[0].split("--");
                        patientfrom = mypatArray[1];
                    }

                    let practitionerAssociatePatient = (event.data && event.data.practitionerAssociatePatient ) ? event.data.practitionerAssociatePatient :  event.practitionerAssociatePatient;
                    if(typeof practitionerAssociatePatient !='undefined' && practitionerAssociatePatient !=null && practitionerAssociatePatient[0]){// practitioner form or not
                        patientfrom = practitionerAssociatePatient[0];
                    }
                    if (patientfrom) {
                        var dataprivacy = { "form_id": validate_form_id, "recipient_id": patientfrom, "staff_prefill_submission_id": formsubmissionid,"curlUrl":url };
                        var settings = {
                            "async": false,
                            "crossDomain": true,
                            "url": 'CorsHttpRequestProxy.php',
                            "method": "POST",
                            "headers": {
                                "content-type": "application/json",
                                "Authentication-Token": decodeURIComponent(loggedAuthKey),
                                "cache-control": "no-cache"
                            },
                            "processData": false,
                            "data": JSON.stringify(dataprivacy)
                        }
                        $.ajax(settings).done(function (resultnew) {
                            resultnew =JSON.parse(resultnew);
                            var msgtxt_hippa;
                            msgtxt_hippa = "<p class='newalerthipaap'>We noticed the changes to the following Form Fields when compared to the pre populated values. Please review & confirm these changes are correct. Patient may get wrong information. If the information is correct, then click on Continue to send the Form. If the information is wrong, click on Cancel to go back to the Form and correct the information and Send again </p> <br/>";
                            var mis_msgtxt = "<table class='newalerthipaa'><tr><th>Field Name</th><th>Current/Changed Value</th><th>Original Value</th></tr>";
                            if (resultnew['status']["statusMessage"] == 'Success' && resultnew['status']["formFieldDataMatched"] == "false") {
                                if (resultnew['formFieldNotMatched']) {
                                    $(jQuery.parseJSON(JSON.stringify(resultnew['formFieldNotMatched']))).each(function () {
                                        mis_msgtxt += "<tr><td>" + this.element_name + "</td><td>" + this.element_current_value + "</td><td>" + this.element_actual_value + "</td></tr>";
                                    });
                                }
                        mis_msgtxt += "</table>";
                        msgtxt_hippa+=mis_msgtxt;
                                setTimeout(function () {
                        $(".swal-modal").css("vertical-align", "top"); 
                        $(".swal-overlay").css("height", $("#form_container").height()); 
                        $(".swal-overlay").css("overflow-y", "auto"); 
                        $(".swal-modal").css("margin-top", "18mm");
                        $(".myclass").css("background-color", "#f39834"); 
                        $(".swal-footer").css("text-align", "center");
                        $(".swal-button--confirm:not([disabled]):hover").css("background-color", "#f39834"); 
                        }, 200);
                        $("html,body").scrollTop(0);
                        var spans = document.createElement("span");
                            spans.innerHTML = msgtxt_hippa;
                            $.postMessage({ formSendLoaderRemove: "true" }, '*');
                            $(".submitLoaderMessage").text('');
                            $(".callbell-loader").hide();
                        swal({
                            html:true,
                            title:"HIPAA ALERT",								
                            content: spans,
                            icon: "error",
                            type: "error",
                            buttonsStyling: false,
                            buttons:
                            {  
                                confirm:
                                {
                                    text: "Continue",
                                    visible: true,
                                    className: "swal-button--cancel",
                                    closeModal: true,
                                }
                                , cancel:
                                {
                                    text: "Cancel",
                                    visible: true,
                                    className: "swal-button--cancel myclass",
                                    closeModal: true,
                                        }
                                }
                                }).then(function (isConfirm) {
                                    const urlParams = new URLSearchParams(window.location.search);
                                    var loggedUsers_id = urlParams.get('toId') ? urlParams.get('toId') : '';
                                    if (isConfirm) {
                                        $.postMessage({ formSendLoader: "true" }, '*');
                                        const ua = navigator.userAgent;
                                        var deviceType='desktop';
                                        if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
                                                    deviceType="tablet";
                                        }else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
                                                    deviceType="mobile";
                                        }
                                        if(deviceType!='desktop'){
                                            $(".submitLoaderMessage").text('Sending the Form. Please wait...');
                                            $(".callbell-loader").show();
                                        }
                                        var data = { 
                                            activityName:"Continue hipaa alert on form sent",
                                            activityType: "Continue hipaa alert on form sent",  
                                            activityDescription:loggedUsers_id +" Continue HIPAA alert on form sent for the form "+ validate_form_id +" - patient - "+patientfrom, 
                                            createdBy:loggedUsers_id,
                                            curlUrl:serverBaseUrlN + "/cometchat/citus-health/v4/track-activity.php"
                                            
                                            };
                                        var settings = {
                                            "async": true,
                                            "crossDomain": true,
                                            "url":'CorsHttpRequestProxy.php' ,
                                            "method": "POST",
                                            "headers": {
                                                "cache-control": "no-cache",
                                                "Access-Control-Allow-Origin": '*',
                                                "authentication-token": decodeURIComponent(loggedAuthKey)
                                            },
                                            "data": data
                                        }
                                        $.ajax(settings);
                                        finalSubmitTop(event);
                                    }
                                    else {
                                        $.postMessage({ SendPatientForm: false }, '*');
                                        var data = { 
                                            activityName:"Cancelled hipaa alert on form sent",
                                            activityType: "Cancelled hipaa alert on form sent",  
                                            activityDescription:loggedUsers_id +" Cancelled HIPAA alert on form sent for the form "+ validate_form_id +" - patient - "+patientfrom, 
                                            createdBy:loggedUsers_id,
                                            curlUrl:serverBaseUrlN + "/cometchat/citus-health/v4/track-activity.php"
                                            
                                            };
                                        var settings = {
                                            "async": true,
                                            "crossDomain": true,
                                            "url":'CorsHttpRequestProxy.php',
                                            "method": "POST",
                                            "headers": {
                                                "cache-control": "no-cache",
                                                "Access-Control-Allow-Origin": '*',
                                                "authentication-token": decodeURIComponent(loggedAuthKey)
                                            },
                                            "data": data
                                        }
                                        $.ajax(settings);
                                        $('input:hidden[name=submit_primary]:not([type=submit])').remove();
                                        $("#send_button_value").remove();
                                        $('#submit_secondary1').prop('disabled', false);
                                        $('.pagination-links').css("pointer-events",'auto');
                                        if($('#submit_primary1').length) $('#submit_primary1').prop('disabled',false);
                                        if($('#submit_form1').length) $('#submit_form1').prop('disabled',false);
                                        if($('#review_submit').length) $('#review_submit').prop('disabled',false);
                                        if($('#review_back').length) $('#review_back').prop('disabled',false);
                                        $('input:hidden[name=review_submit]:not([type=submit])').remove();
                                        localStorage.removeItem('notShowPopup');
                                    }
                                });
                            }
                            else {
                                finalSubmitTop(event);
                            }
                        });
                    }
                    else {
                        finalSubmitTop(event);
                    }
                }
                else {
                    finalSubmitTop(event);
                }
            }
            else {
                finalSubmitTop(event);
            }


        }

    }


    $(document).on('change', '#sites-select', function () {
        var lengthoptions = $('#sites-select > option').length;
        var lengthselected = $("#sites-select :selected").length;
        if (lengthoptions == lengthselected) {
            $(".chkclass #chkall").prop("checked", "checked");
        } else {
            $(".chkclass #chkall")[0].checked = false;
        }
    });


    $(document).on('click', '.chkclass #chkall', function () {
        if ($(".chkclass #chkall").is(':checked')) {
            $("#sites-select > option").prop("selected", "selected");
            $("#sites-select").trigger("change");
            $(".dynamicContent .select2-selection").css('overflow', 'auto')
        } else {

            $("#sites-select > option").removeAttr("selected");
            $("#sites-select").val("");
            $("#sites-select").trigger("change");
            $(".dynamicContent .select2-selection").css('overflow', 'auto')
        }
    });
    // extract master class name from the whole elements
    var classnearSearchtext;
    var classArray = [];
    $.each($('[class*="mdm_"]'), function (key, value) {
        classnearSearchtext = $(this).attr('class');
        classnearSearchtext = classnearSearchtext.replace('highlighted', "");
        classnearSearchtext = classnearSearchtext.replace(/(^|\s)column\S+/g, '');
        if (classnearSearchtext.indexOf('--') == -1) {
            classArray.push(classnearSearchtext)
        }
    });


    // clear all input field after open and close of modal
    $('#dynamicelementsModal').on('shown.bs.modal', function (e) {
        var index = $("#indexvalue").val();
        var classname = $('#searchCssClass').val();
        $('.dynamicContent :input').not('.button_text,#sites-select').val('')
        $(".dynamicContent ." + classname).find('input').val($("#searchKeyword").val());
        $("#errorvalidation").html("");
        $("#errorvalidation").hide();
    })

    $('#dynamicelementsModal').on('hide.bs.modal', function (e) {
        $('.dynamicContent :input').not('.button_text').val('')
        $("#errorvalidation").html("");
        $("#errorvalidation").hide();
        $(".dynamicContent").html('');
        requiredArray = [];
    })
    function saveAsDraftMessage() {

        //mobile app message change
      if(initialDraft != 1){
        $.postMessage({ saveasdraftCompleted: "autosaveasdraft" }, '*');
        if ($(".message-save-as-draft").length) {
            var localTime = moment().format("MMM D, LT"); 
            let localTimeArray = localTime.split(",");
            localTime = localTime.replace(",","");
            $(".message-save-as-draft").html("");
            if (draftFail == 0) {
                $("#currentdrfttime").val(localTime);
                $("#prevdrfttime").val(localTime);
                $(".message-save-as-draft").html("<div style='font-size:12px;margin:7px'>This form was automatically Saved as Draft at " + localTimeArray[1] + " and can also be found in the Drafts category of your Form Worklist.</div>")
            } else {
                $("#currentdrfttime").val($("#prevdrfttime").val());
                //$("#prevdrfttime").val("");
                let prevTime = "";
                if ($("#currentdrfttime").val() != "") {
                    prevTime = "(last saved at " + $("#currentdrfttime").val() + ")";
                }
                $(".message-save-as-draft").html("<div style='font-size:12px;margin:7px;color:red'>Automatic Save As Draft operation failed at " + localTimeArray[1] + " " + prevTime + ".Please use Save As Draft operation at the end of the Form to save your work periodically.</div>")
            }

            if (localStorage.getItem('myUniqueKey') != null && localStorage.getItem('myUniqueKey') != undefined) {
                localStorage.setItem(localStorage.getItem('myUniqueKey') + '_id', 1);
                localStorage.setItem(localStorage.getItem('myUniqueKey') + '_message', $(".message-save-as-draft").html());
                $(".message-save-as-draft").html(localStorage.getItem(localStorage.getItem('myUniqueKey') + '_message'));
            }

        }
     }
        //mobile app message change
    }

    $("#form_container").delegate("*", "focus blur", function () {

        var elem = $(this);
        if ($(this).attr("type")) {
            setTimeout(function () {
                elem.toggleClass("focused", elem.is(":focus"));
            }, 0);
        }

    });

    $(".multiple_choice :radio").click(function () {

        var $this = $(this);
        var attr = $this.attr('ischecked');
        var names = $this.attr('name');
        if (typeof attr !== typeof undefined && attr !== false) {


            $('.' + names).removeAttr('ischecked');

            $this.removeAttr("ischecked");
            $this.prop('checked', false);
            if(!$this.hasClass('focused')) return; 
            var clickedelementParent = $this.closest('.pre_populate_confirm').attr("id");
            if (clickedelementParent) var id = clickedelementParent.split("_")[1]; else var id = null;
            if ($("#" + clickedelementParent + " .confirm_link").length) {
    
                $("#" + clickedelementParent + " .confirm_link").remove();
                $("#" + clickedelementParent + " .not_confirmed_class").remove();
                $("#" + clickedelementParent).css("border", "none");
                $("#" + clickedelementParent + " .confirm_error_present").remove();
            }
            $("#" + clickedelementParent).removeClass("confirmprefill");
            $("#" + clickedelementParent).addClass("valueChangedElement");
            if(!$("#element_changed_"+id).length && id!=null) $("#" + clickedelementParent).append("<input type='hidden' id='element_changed_" + id + "' name='element_changed_" + id + "' class='element_changed_class' value='" + id + "'>");



        } else {


            $('.' + names).removeAttr('ischecked');

            $this.attr("ischecked", 1);
            $this.prop('checked', true);

        }

    });

    $("input[type=radio]:checked").each(function () {
        $(this).attr("ischecked", 1);

    });
    $(".multiple_choice .other").click(function () {
        var input = $(this).parent("span").find(":radio");
        if(!input.is(':checked')){
        input.attr("ischecked", 1);
        setTimeout(function () { input.prop('checked', true); }, 0);
        }
    });

    $(".matrix :radio").click(function () {
        var parent_id = $(this).closest(".matrix").attr("id");
        var $this = $(this);
        var attr = $this.attr('ischecked');
        if (typeof attr !== typeof undefined && attr !== false) {
            $("#" + parent_id + " :radio").each(function () {
                this.removeAttribute("ischecked");
            });
            $this.removeAttr("ischecked");
            setTimeout(function () { $this.prop('checked', false); }, 0);
        } else {
            $("#" + parent_id + " :radio").each(function () {
                this.removeAttribute("ischecked");
            });
            $this.attr("ischecked", 1);
            setTimeout(function () { $this.prop('checked', true); }, 0);
        }
    });






    var formElements = [];
    var checkJson = false;
    var matrix = [];
    var submissionidNew = 0;
    var practitionerid = 0;
    var subid = 0;
    var clientId = 0;
    localStorage.setItem('donottrigger', 0);
    localStorage.setItem("pagenavigationclicked", 0);
    localStorage.setItem("pagenavigationtopclick", 0);
    localStorage.setItem('navigatedpages', 0);

    var referrer = document.referrer;


    var documentreferrer = document.referrer;
    if (getQueryStringOld().back == "true" || getQueryStringOld().back == true) {
        localStorage.setItem('confirm_back', 1);
    }
    var idcheck = getQueryStringCheck().id;
    var formName = getQueryString().formName;
    /***New Variables for collaborate Edit***/
    var enableCollaborateEdit = getQueryString().enableCollaborateEdit;
    if (parseInt(enableCollaborateEdit) == 1) {
        localStorage.setItem('enableCollaborateEdit', enableCollaborateEdit);
    }
    if (parseInt(enableCollaborateEdit) == 0) {
        localStorage.setItem('enableCollaborateEdit', 0);
    }

    var populatePreviousSubmission = getQueryString().populatePreviousSubmission;
    if (populatePreviousSubmission == 'true') {
        localStorage.setItem('populatePreviousSubmission', 1);
    }
    else {
        localStorage.setItem('populatePreviousSubmission', 0);
    }

    var formidn = getQueryString().id;

    if (localStorage.getItem('populatePreviousSubmission') == 1 && formidn && getQueryString().formCleared == "true") {



        localStorage.setItem('donottrigger', 1);
        if (localStorage.getItem('datapopulatefromsubmission') != "") {

            checkJson = IsValidJSONString(localStorage.getItem('datapopulatefromsubmission'));


            if (checkJson == true) {
                var response = jQuery.parseJSON(localStorage.getItem('datapopulatefromsubmission'));
                if(typeof response!=='undefined' && response!=null){
                    var arr = response['elements']
                    var obj_arr = response['results']  
                } 
                var resultObj = {};
                // get all the keys from the object
                if (typeof arr!=='undefined' && typeof obj_arr!=='undefined' && obj_arr) {


                    var getAllKeys = Object.keys(obj_arr);
                    arr.forEach(function (item) {
                        // looping through first object 
                        getAllKeys.forEach(function (keyName) {
                            // using index of to check if the object key name have a matched string
                            var itemupdated = item + '_';

                            if (keyName.indexOf(itemupdated) !== -1 || keyName == item) {
                                resultObj[keyName] = obj_arr[keyName];
                            }
                        })
                    })

                    for (var key in resultObj) {
                        if (resultObj.hasOwnProperty(key)) {
                            if ($("#" + key).length) {
                                if ($("#" + key).parent().parent().parent().parent().hasClass('checkboxes')) {
                                   if (localStorage.getItem("visitedpagess") !== null) {
									   
                                        var pagesvisited = JSON.parse(localStorage.getItem("visitedpagess"));
                                        var foundValues = pagesvisited.filter(obj => obj.id ===  getQueryString().uniqueFormIdentity);
                                        if (foundValues[0].value && $("input[name=page_number]").val()) {
                                            var pageIds = foundValues[0].value.toString().split('-');
                                            if (!pageIds.includes($("input[name=page_number]").val()) || (pageIds.length == 1 && pageIds == 1)) {
                                                if ($("#" + key).is(":checked") || getQueryString().staffSubmissionId && getQueryString().staffSubmissionId != null && getQueryString().staffSubmissionId == "null") {

                                                } else {
                                                    if (resultObj[key] == 1) {
                                                        $("#" + key).prop('checked', false);
                                                        $("#" + key).attr('checked', false);
                                                        $("#" + key).trigger("click");
                                                        
                                                    } else {
                                                        $("#" + key).prop('checked', false);
                                                        $("#" + key).attr('checked', false);
                                                    }
                                                }
                                            }
                                            }
                                            
                                        }
                                }


                                if ($("#" + key).hasClass('select') && $("#" + key).val() == "") {
                                    $("#" + key).val(resultObj[key]).change();

                                }
                                if ($("#" + key).val() == "" || $("#" + key).attr("placeholderforcheck") == $("#" + key).val())
                                {
                                    if (localStorage.getItem("visitedpagess") !== null) {
                                        var formUniqueId = getQueryString().uniqueFormIdentity;
                                        var pagesvisited = JSON.parse(localStorage.getItem("visitedpagess"));
                                        var foundValues = pagesvisited.filter(obj => obj.id === formUniqueId);
                                        if (foundValues.length && foundValues[0].value && $("input[name=page_number]").val()) {
                                            var pageIds = foundValues[0].value.toString().split('-');
                                            if (!pageIds.includes($("input[name=page_number]").val())) {
                                                $("#" + key).val(resultObj[key]);
                                            }
                                        }
                                    } 
                                    else
                                    {
                                        $("#" + key).val(resultObj[key]);
                                    }
                                }

                            } else {
                                if ($('input[name="' + key + '"]').attr("type") == "radio" && $('input[name="' + key + '"]').is(":checked") == false) {
                                    if (resultObj[key]) {


                                        $('input[name="' + key + '"]' + '[value="' + resultObj[key] + '"]').prop('checked', false);
                                        $('input[name="' + key + '"]' + '[value="' + resultObj[key] + '"]').attr('checked', false);
                                        $('input[name="' + key + '"]' + '[value="' + resultObj[key] + '"]').trigger("click");

                                    } else {

                                        $('input[name="' + key + '"]' + '[value="' + resultObj[key] + '"]').prop('checked', false);
                                        $('input[name="' + key + '"]' + '[value="' + resultObj[key] + '"]').attr('checked', false);
                                    }

                                }


                                if ($("#" + key + '_1').parent().attr('class') == "date_mm") {
                                    if (resultObj[key]) {
                                        var string = resultObj[key].split("-");


                                        if ($("#" + key + '_1').val() == "") {
                                            $("#" + key + '_1').val(string[1]);
                                            $("#" + key + '_2').val(string[2]);
                                            $("#" + key + '_3').val(string[0]);
                                        }
                                    }

                                }

                                if ($("#" + key + '_1').parent().attr('class') == "main_currency") {

                                    if (resultObj[key]) {

                                        // setTimeout(function(){  
                                        var string = resultObj[key].split(".");


                                        if ($("#" + key + '_1').val() == "") {
                                            $("#" + key + '_1').val(string[0]);
                                            $("#" + key + '_2').val(string[1]);

                                        }

                                    }

                                }
                                if ($("#" + key + '_1').parent().parent().parent().hasClass("time_field")) {
                                    if (resultObj[key]) {
                                        var string = resultObj[key].split(":");

                                        if ($("#" + key + '_1').val() == "") {
                                            $("#" + key + '_1').val(string[0]);
                                            $("#" + key + '_2').val(string[1]);
                                        }
                                        if ($("#" + key + '_4').length) {
                                            if (string[0] >= 13) {
                                                $("#" + key + '_4').val("PM")
                                                $("#" + key + '_1').val(string[0] - 12);
                                            }
                                        }
                                    }
                                }

                                if ($("#" + key + '_1').parent().attr('class') == "phone_1") {
                                    var strFirstThree = resultObj[key].substring(0, 3);
                                    var strSecondThree = resultObj[key].slice(3, 6);
                                    var strThridFour = resultObj[key].slice(6, 10);
                                    if ($("#" + key + '_1').val() == "") {
                                        $("#" + key + '_1').val(strFirstThree);

                                        $("#" + key + '_2').val(strSecondThree);

                                        $("#" + key + '_3').val(strThridFour);

                                    }
                                }

                            }
                            let text = key;
                            var Check_other = text.includes("_other");
                            if (Check_other === true) {
                                if (localStorage.getItem("visitedpagess") !== null) {
                                    var formUniqueId = getQueryString().uniqueFormIdentity;
                                    var pagesvisited = JSON.parse(localStorage.getItem("visitedpagess"));
                                    var foundValues = pagesvisited.filter(obj => obj.id === formUniqueId);
                                    if (foundValues[0].value && $("input[name=page_number]").val()) {
                                        var pageIds = foundValues[0].value.toString().split('-');
                                        if (!pageIds.includes($("input[name=page_number]").val()) || (pageIds.length == 1 && pageIds == 1)) {
                                            if (resultObj[key] != '' && resultObj[key] != null) {
                                                let res_id = text.replace("_other", "");
                                                $('#' + res_id + "_0").prop('checked', true);
                                            }
                                        }
                                    }
                                } else {
                                    if (resultObj[key] != '' && resultObj[key] != null) {
                                        let res_id = text.replace("_other", "");
                                        $('#' + res_id + "_0").prop('checked', true);
                                    }
                                }
                            } 

                        }
                    }
                    localStorage.setItem('donottrigger', 0);
                }
            }
        }

    }

    var fromMob = false;
    if (getQueryString().fromMob == 'true' || getQueryString().fromMob == true) {
        fromMob = true;
    }
    /***New Variables for collaborate Edit***/

    /***New Variables***/

    var timeIntervalToSaveDraft = parseInt(getQueryString().saveAsDraftMessageInterval) * 60;
    if (getQueryString().saveAsDraftMessageInterval == null || getQueryString().saveAsDraftMessageInterval == "null" || getQueryString().saveAsDraftMessageInterval == "") {
        var timeIntervalToSaveDraft = 5 * 60;
    }
    var Countdown = null;
    var counter = '';
    var saveDraftValue = false;


    //
    if (getQueryString().formName) {
        formName = formName.replace(/%20/g, ' ');
        formName = formName.replace(/\+/g, ' ');
        formName = decodeURIComponent(formName);
    }



    var externalFileExchange = getQueryString().externalFileExchange;
    if (getQueryString().externalFileExchange == "true" || getQueryString().externalFileExchange == true) {
        externalFileExchange = true;
    } else {
        externalFileExchange = false;
    }
    /*$("input.text").each(function () {
        if ($(this).val() == 0 && $(this).attr('size') != 2) {
            $(this).val('');
        }

    });*/
    function IsValidJSONString(str) {
        try {
            JSON.parse(str);
        } catch (e) {
            return false;
        }
        return true;

    }
    function setCookie(name, value, days) {
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "") + expires + "; path=/";
    }
    function intimate_user_to_save(clearTimeOut = true, onDrafting = true, existingCounter = 0) {

        if (!$.isNumeric(timeIntervalToSaveDraft) || timeIntervalToSaveDraft <= 0) return false;
        if (savaAsDraftStaff != 1 || (getQueryString().staffFilling == false && getQueryString().staffFacing == false) || (getQueryString().staffFilling == "false" && getQueryString().staffFacing == "false")) {

            return false;
        }
        if (getQueryString().AllowEdit && (getQueryString().AllowEdit == 'true' || getQueryString().AllowEdit == true)) {

            return false;
        }

        if (onDrafting == true || (getQueryString().pendingView == true || getQueryString().pendingView == 'true')) {

            clearInterval(Countdown);
            counter = "";
            return true;
        } else {
            if (clearTimeOut == true) Countdown ? clearInterval(Countdown) : '';
            counter = existingCounter ? existingCounter : 1;
            Countdown = setInterval(function () {
                counter++
                if (counter === timeIntervalToSaveDraft) {
                      
                    /****Message to user on inactivity****/
                    $(".appnitro").attr("automaticdraftsave", 1);

                    localStorage.setItem("automaticDraft", 1);
                    $('#save_as_draft_submit_form').trigger("click");
                    $.postMessage({ saveasdraftCompleted: "autosaveasdraft" }, '*');

                    clearInterval(Countdown);
                    counter = "";
                    if (localStorage.getItem('exsitingCounter')) localStorage.removeItem('exsitingCounter');
                    intimate_user_to_save(false, false, 0);



                }
            }, 1000);
        }

    }

    $(document).ready(function () {
        $(".appnitro input").attr("autocomplete", "off"); 
        var urlDisable = window.location.href;
        var staffillDisable = 0;
        var staffFacingDisable = 0;
        var createsendDisable = 0;
        var paramsStaffil = urlDisable.split('?')[1].split('&'); 
        for(var staffillDisablei = 0;staffillDisablei<paramsStaffil.length;staffillDisablei++){
            var staffillDisabletemp = paramsStaffil[staffillDisablei].split('=');
            var staffillDisablekey   = staffillDisabletemp[0];
            var staffillDisablevalue = staffillDisabletemp[1];
            console.log(staffillDisablekey +':'+staffillDisablevalue);
            if(staffillDisablekey == "staffFilling" && (staffillDisablevalue == false || staffillDisablevalue == "false" )){
                 staffillDisable = 1;
            }
            if( staffillDisablekey == "staffFacing" && (staffillDisablevalue == "practitioner" ||  ( typeof staffillDisablevalue  === 'boolean' && staffillDisablevalue == false)  || staffillDisablevalue == "false")){
                staffFacingDisable = 1;
           }
           if( staffillDisablekey == "create_send" && (staffillDisablevalue == "true" || staffillDisablevalue == true)){
               createsendDisable = 1;
            }
        }
        var active_page_review = 0;
        if ($("#review_submit").length) active_page_review = 1;
       // if((getQueryString().staffFilling == false && getQueryString().staffFacing == false && (getQueryString().create_send == true ||  getQueryString().create_send == 'true')) || (getQueryString().staffFilling == "false" && getQueryString().staffFacing == "false" && (getQueryString().create_send == true ||  getQueryString().create_send == 'true') )){
          if(staffillDisable == 1 && staffFacingDisable == 1 && createsendDisable == 1 && active_page_review == 0 ){
            $("#form_container form").css("pointer-events", "none"); 
            setTimeout(function(){  
                $("#form_container").css("cursor","not-allowed");
            }, 300);
           
        }

        if(getQueryString().completedFormsRecipients){// query string check in the case of mobile & clear form button click
            var sCompletedFormsRecipients = getQueryString().completedFormsRecipients;
            var aCompletedFormsRecipients = sCompletedFormsRecipients.split('---').filter(element => element.trim() != '');
            var completedFormsRecipients = "";
            if(aCompletedFormsRecipients.length > 0){
                completedFormsRecipients =  sCompletedFormsRecipients.replace(/---/g, ",");
                if(!$("#completed-forms-recipients").length) {
                    $("#li_buttons").append('<input type="hidden" id="completed-forms-recipients" value="' + completedFormsRecipients +' " name="completed-forms-recipients" />');
                } else {
                    document.getElementById("completed-forms-recipients").value = completedFormsRecipients;
                }
            }
        }
        formpushmode = $("#formpushmode").val();
        window.parent.postMessage({ formIframeHeight: $(document).height() }, "*"); 
        localStorage.removeItem("notShowPopup");
        //mobile app message change    
        if (getQueryString().screenOrientationMobile && getQueryString().savedDraftid > 0 && getQueryString().id) {
            var serverBaseUrl = baseurlLogged;
            var serverBaseUrlN = serverBaseUrl.replace("%3A%2F%2F", "://");
            var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
            var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
            var url = serverBaseUrlN + '/cometchat/citus-health/v4/get-all-drafts-form-details.php';
            var settings = {
                "async": false,
                "crossDomain": true,
                "url": 'CorsHttpRequestProxy.php',
                "method": "POST",
                "headers": {
                    "content-type": "application/json",
                    "authentication-token": decodeURIComponent(loggedAuthKey),
                    "cache-control": "no-cache"
                },
                "processData": false,
                "data": JSON.stringify({
                    formid: getQueryString().id,
                    submissionid: getQueryString().savedDraftid,curlUrl:url
                })
            }
            $.ajax(settings).done(function (response) {
                const lastDraftSavedDate = new Date(JSON.parse(response)[0]['modifiedAT']*1000);
                let localDate = lastDraftSavedDate.toLocaleString("en-US",{month: 'short',day: '2-digit',hour: 'numeric',minute: 'numeric',hour12: true});
                localDate = localDate.replace(",","");
                console.log("cloalDate"+localDate)
                $("#currentdrfttime").val(localDate);
                $("#prevdrfttime").val(localDate);
            });
        }


        //mobile app message change     



        var create_send = true;
        if (getQueryString().sentId && getQueryString().sentId != null && getQueryString().sentId != 'null' && getQueryString().sentId != 'undefined') {
            $(".manage-role-btn").hide();
            create_send = false;
        }


        var draftEditing = false;
        if (getQueryString().staffSubmissionId && getQueryString().staffSubmissionId !== null && getQueryString().staffSubmissionId != 'undefined' && getQueryString().staffSubmissionId > 0) {
            draftEditing = true;
            create_send = false;
        }
        if (getQueryString().savedDraftid && getQueryString().savedDraftid !== null && getQueryString().savedDraftid != 'undefined' && getQueryString().savedDraftid > 0 && (!getQueryString().AllowEdit || getQueryString().AllowEdit == false || getQueryString().AllowEdit == 'false')) {
            create_send = false;
            var draftEditing = true;
        }
        if ((getQueryString().AllowEdit && (getQueryString().AllowEdit == false || getQueryString().AllowEdit == 'false'))) {
            draftEditing = false;
        }
        else {
            draftEditing = true;
        }
        if (getQueryString().AllowEdit && (getQueryString().AllowEdit == true || getQueryString().AllowEdit == 'true')) {
            create_send = false;
        }
        const storedKey = localStorage.getItem("myUniqueKey");
        const queryStringKey = getQueryString().uniqueFormIdentity;
        if (!storedKey || storedKey !== queryStringKey) {
            localStorage.setItem("completedFormsRecipientsStorage", "");
        }
        // session unique in multiple tabs checking
        if ((getQueryString().receipientCount == 1 || getQueryString().receipientCount == 0) && create_send == true && $("#save_as_draft_submit_form").length && (localStorage.getItem('saveasdraftidtodeleted') === null || localStorage.getItem('saveasdraftidtodeleted') == 0 || localStorage.getItem('saveasdraftidtodeleted') == 'false' || localStorage.getItem('saveasdraftidtodeleted') == false || localStorage.getItem('saveasdraftidtodeleted') == 'undefined')) {
            localStorage.setItem('automaticDraft', 1);
            localStorage.setItem('automatic', 1);
            localStorage.setItem("notShowPopup", 1);
            $("#save_as_draft_submit_form").trigger('click');
            console.log("---------------------1654");
            
        }
        
        if((getQueryString().receipientCount > 1) && create_send == true){
            
            var serverBaseUrlN = getQueryString().serverBaseUrl.replace("%3A%2F%2F", "://");
                serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
                serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
            var datas = { 
                
                curlUrl:serverBaseUrlN + "/cometchat/citus-health/v4/delete-draft-form.php",
                formId:getQueryString().formId,
                formDatadraftid:localStorage.getItem("fileSaveDraftId")

                };
            var settings = {
                "async": true,
                "crossDomain": true,
                "url":'CorsHttpRequestProxy.php' ,
                "method": "POST",
                "headers": {
                    "cache-control": "no-cache",
                    "Access-Control-Allow-Origin": '*',
                    "authentication-token": decodeURIComponent(authToken)
                },
                "data": datas
            }
            $.ajax(settings);
        }
        // session unique in multiple tabs checking
        localStorage.removeItem('automaticDraft');

        if (draftEditing == true) {

            $("#submit_secondary").click(function (evt) {
                if ($('#save_as_draft_allow_edit').length) {

                    localStorage.setItem("automaticDraft", 1);



                }
                if (localStorage.getItem("pagenavigationtopclick") == 1) {


                } else {

                    var active_page = parseInt($(".ap_tp_num_active").text());
                    var newPageNumber = active_page - 1;
                    localStorage.setItem('navigatedpages', active_page + ' to ' + newPageNumber);

                }
                if ($("#save_as_draft_submit_form").length) {
                    localStorage.setItem("automaticDraft", 1);
                    localStorage.setItem('automatic', 1);



                    if (window.location.href.indexOf("/view.php") == -1 && window.location.href.indexOf("/get-form-html.php") == -1 ) {
                        saveAsDraftMessage();
                    }


                    setTimeout(myFunction, 1000);
                    function myFunction() {
                        if (localStorage.getItem("draftsuccess")) {
                            localStorage.setItem("goprev", 1);
                            return true;
                        } else {
                            evt.preventDefault();
                        }
                    }
                }
            });
        }





        var formUniqueId = getQueryString().uniqueFormIdentity;
        if (localStorage.getItem("myUniqueKey") === null || typeof localStorage.getItem("myUniqueKey") === 'undefined') {
            localStorage.removeItem("fileSaveDraftId");
            localStorage.setItem('saveasdraftidtodeleted', 'false');
            $.postMessage({ saveasdraftidtodeleted: 'false' }, '*');

            localStorage.setItem("myUniqueKey", formUniqueId);
            localStorage.removeItem("numberfields");
            localStorage.removeItem("numberfieldsMoney");
            localStorage.removeItem('recepientsCountMsg');
            var recepientsCount = getQueryString().receipientCount;
            if (getQueryString().receipientCount) {
                localStorage.setItem('recepientsCountMsg', getQueryString().receipientCount);

            }

        }
        if (localStorage.getItem("myUniqueKey") && localStorage.getItem("myUniqueKey") != formUniqueId) {
            localStorage.setItem('saveasdraftidtodeleted', 'false');
            $.postMessage({ saveasdraftidtodeleted: 'false' }, '*');

            localStorage.removeItem("fileSaveDraftId");
            localStorage.setItem("myUniqueKey", formUniqueId);
            localStorage.removeItem("numberfields");
            localStorage.removeItem("numberfieldsMoney");
            localStorage.removeItem('recepientsCountMsg');
            var recepientsCount = getQueryString().receipientCount;
            if (getQueryString().receipientCount) {
                localStorage.setItem('recepientsCountMsg', getQueryString().receipientCount);

            }

        }
        if ($(".numfield_class_money").length) {

            if (localStorage.getItem("numberfieldsMoney") && localStorage.getItem("numberfieldsMoney").length) {

                var x = JSON.parse(localStorage.getItem("numberfieldsMoney"));

            } else {

                var x = [];
            }

            $(".numfield_class_money").each(function (index) {
                var id = $(this).attr("id");
                id = id.split("_");
                id = id[0] + "_" + id[1]
                if (x.indexOf(id) === -1) x.push(id);
            });
            localStorage.removeItem("numberfieldsMoney");
            localStorage.setItem("numberfieldsMoney", JSON.stringify(x));


        }


        if ($(".numfield_class").length) {
            if (localStorage.getItem("numberfields") && localStorage.getItem("numberfields").length) {
                var x = JSON.parse(localStorage.getItem("numberfields"));

            } else {
                var x = [];
            }

            $(".numfield_class").each(function (index) {
                var id = $(this).attr("id");
                if (x.indexOf(id) === -1) x.push(id);
            });
            localStorage.removeItem("numberfields");
            localStorage.setItem("numberfields", JSON.stringify(x));

        }
        if ($(".showZero").length) {

            $(".showZero").each(function (index) {

                $(this).val("0");
            });
        }
        if ($(".showNull").length) {
            $(".showNull").each(function (index) {
                $(this).val("");
            });
        }
        if (getQueryString().formId && (getQueryString().AllowEdit == 'true' || getQueryString().AllowEdit == true) && getQueryString().FormEntryID) {
            formid = getQueryString().formId;
            FormEntryID = getQueryString().FormEntryID;
            $("#form_" + formid).append('<input type="hidden" value="' + FormEntryID + '" name="EditID">');


        }

        if ($("#review_submit").length) active_page = 'review page';
        else if ($(".ap_tp_num_active").length) active_page = parseInt($(".ap_tp_num_active").text());
        else active_page = 1;

        if (getQueryString().clearForm && getQueryString().clearForm == 1) {
            var prev_page = localStorage.getItem('activityPageNumber');
            /**********Call Track Activity On Clear Form**/
            let form_id = getQueryString().formId;
            let ActivityType = "Clear Form";
            $.ajax({
                type: "POST", async: false, crossDomain: true, headers: { "cache-control": "no-cache", "Access-Control-Allow-Origin": '*' },
                url: "ajax-track-activity.php",
                data: { form_id: form_id, ActivityType: ActivityType, prev_page: prev_page },
                success: (result) => {

                }
            });
            /*************Activity Ends.******/
            localStorage.setItem('activityPageNumber', active_page);
        } else {
            localStorage.setItem('activityPageNumber', active_page);
        }



        if (localStorage.getItem('exsitingCounter') && localStorage.getItem('exsitingCounter') > 0) {
            intimate_user_to_save(false, false, localStorage.getItem('exsitingCounter'));

            localStorage.removeItem('exsitingCounter');
        }
        /**Consolo Code***/
        if (!getQueryString().clearForm || typeof getQueryString().clearForm == 'undefined' || getQueryString().clearForm == 0 || getQueryString().clearForm == '0') {
            if (getQueryString().patientData && getQueryString().patientData != null && typeof getQueryString().patientData != 'undefined' && getQueryString().patientData != '' && getQueryString().patientData != 'undefined' && getQueryString().patientData != 'null' && getQueryString().patientData != 'NULL') var patient = JSON.parse(decodeURIComponent(getQueryString().patientData)); else patient = null;
            if (getQueryString().patientMRN && getQueryString().patientMRN != null && typeof getQueryString().patientMRN != 'undefined' && getQueryString().patientMRN != '' && getQueryString().patientMRN != 'null' && getQueryString().patientMRN != 'NULL') var patientMRN = decodeURIComponent(getQueryString().patientMRN); else var patientMRN = null;
            if (patient && typeof patient != 'undefined') {
                if (patient.firstName && patient.firstName != null && patient.firstName != 'null' && patient.firstName != 'NULL' && patient.firstName != 'undefined' && patient.firstName != '') var patientFirstName = patient.firstName;
                else var patientFirstName = null;
                if (patient.lastName && patient.lastName != null && patient.lastName != 'null' && patient.lastName != 'NULL' && patient.lastName != 'undefined' && patient.lastName != '') var patientLastName = patient.lastName;
                else var patientLastName = null;
                if (patient.dob && patient.dob != null && patient.dob != 'null' && patient.dob != 'NULL' && patient.dob != 'undefined' && patient.dob != '') var patientDob = patient.dob;
                else var patientDob = null;
                if (patient.gender && patient.gender != null && patient.gender != 'null' && patient.gender != 'NULL' && patient.gender != 'undefined' && patient.gender != '') var patientGender = patient.gender;
                else var patientGender = null;
                if (patient.email && patient.email != null && patient.email != 'null' && patient.email != 'NULL' && patient.email != 'undefined' && patient.email != '') var patientEmail = patient.email;
                else var patientEmail = null;
                if (patient.mobile && patient.mobile != null && patient.mobile != 'null' && patient.mobile != 'NULL' && patient.mobile != 'undefined' && patient.mobile != '') var patientMobile = patient.mobile;
                else var patientMobile = null;
                if ($("li.patient-name").length || $("li.patient_name").length) {
                    var element_id = $("li.patient-name").length ? $("li.patient-name").attr("id") : $("li.patient_name").attr("id");
                    var ids = element_id.split('_');
                    var id = ids[1];
                    if ($("li.patient-name").hasClass("simple_name") || $("li.patient_name").hasClass("simple_name")) {
                        if (patientFirstName != null) $("#element_" + id + "_1").val(patientFirstName);
                        if (patientLastName != null) $("#element_" + id + "_2").val(patientLastName);
                    }
                    if ($("li.patient-name").hasClass("simple_name_wmiddle") || $("li.patient_name").hasClass("simple_name_wmiddle")) {
                        if (patientFirstName != null) $("#element_" + id + "_1").val(patientFirstName);
                        if (patientLastName != null) $("#element_" + id + "_3").val(patientLastName);
                    }
                }
                if (($("li.patient-email").length || $("li.patient_email").length) && patientEmail != null) {
                    var element_id = $("li.patient-email").length ? $("li.patient-email").attr("id") : $("li.patient_email").attr("id");
                    var ids = element_id.split('_');
                    var id = ids[1];
                    $("#element_" + id + "").val(patientEmail);

                }
                if (($("li.patient-mrn").length || $("li.patient_mrn").length) && patientMRN != null && patientMRN.length < 11 && (patientMRN.match(/-/g) || []).length < 3) {
                    var element_id = $("li.patient-mrn").length ? $("li.patient-mrn").attr("id") : $("li.patient_mrn").attr("id");
                    var ids = element_id.split('_');
                    var id = ids[1];
                    $("#element_" + id + "").val(patientMRN);
                }
                if (($("li.patient-phone").length || $("li.patient_phone").length) && patientMobile) {
                    var element_id = $("li.patient-phone").length ? $("li.patient-phone").attr("id") : $("li.patient_phone").attr("id");
                    var ids = element_id.split('_');
                    var id = ids[1];
                    var str = patientMobile.replace(/[^a-zA-Z0-9]/g, '');
                    var first = str.slice(0, 3);
                    var second = str.slice(3, 6);
                    var third = str.slice(6, 10);
                    $("#element_" + id + "_1").val(first);
                    $("#element_" + id + "_2").val(second);
                    $("#element_" + id + "_3").val(third);

                }
                if (($("li.patient-dob").length || $("li.patient_dob").length) && patientDob) {
                    var element_id = $("li.patient-dob").length ? $("li.patient-dob").attr("id") : $("li.patient_dob").attr("id");
                    var ids = element_id.split('_');
                    var id = ids[1];
                    var date = patientDob.split('-');
                    var month = date[1];
                    var day = date[2];
                    var year = date[0];
                    $("#element_" + id + "_1").val(month);
                    $("#element_" + id + "_2").val(day);
                    $("#element_" + id + "_3").val(year);
                    $("#element_" + id + "_1").trigger("click");
                    $("#element_" + id + "_2").trigger("click");
                    $("#element_" + id + "_3").trigger("click");

                }
                if (($("li.patient-gender").length || $("li.patient_gender").length) && patientGender) {
                    var element_id = $("li.patient-gender").length ? $("li.patient-gender").attr("id") : $("li.patient_gender").attr("id");
                    var ids = element_id.split('_');
                    var id = ids[1];
                    if (patientGender == 1) $("#element_" + id + "_1").prop("checked", true);
                    else if (patientGender == 2) $("#element_" + id + "_2").prop("checked", true);


                }
            }
        }
        /**Consolo Ends here. */
        /*$(".date_of_service input[type!=hidden]").on('keyup change',function(){
            var id = $(this).attr("id");
            if(id!='') var idArray=id.split("_");
            var europian = $(this).closest('li').hasClass('europe_date_field')?true:false;
            var normalDate = $(this).closest('li').hasClass('date_field')?true:false;
            if(idArray[1] && (europian || normalDate)){
                 var day = europian ? $("#element_"+idArray[1]+"_1").val():$("#element_"+idArray[1]+"_2").val();
        
                 var month = europian ? $("#element_"+idArray[1]+"_2").val():$("#element_"+idArray[1]+"_1").val();
        
                 var year = $("#element_"+idArray[1]+"_3").val()
                 if(day=='' || month=='' || year==''){
                    
                     $(".date-of-service").text("");
                 }else{
                    var monthFormatted= (month.toString().length<2)?"0"+month:month;
                    var dateFormatted = (day.toString().length<2)? "0"+day:day;
                     $(".date-of-service").text("- DOS "+monthFormatted+"-"+dateFormatted+"-"+year); 
                     $.postMessage({ dosUpdate: "- DOS "+monthFormatted+"-"+dateFormatted+"-"+year }, '*');
                 }
        
                
            }
        });*/

    });

    if (localStorage.getItem('exsitingCounter') && localStorage.getItem('exsitingCounter') > 0) intimate_user_to_save(false, false, localStorage.getItem('exsitingCounter'));


    /*==========================================================PAGE NAVIGATION=============================================================================*/
    $(document).ready(function () {

        if (getQueryString().formId && (getQueryString().AllowEdit == 'true' || getQueryString().AllowEdit == true) && getQueryString().FormEntryID) {


            $("#form_" + formid).append('<input id="save_as_draft_allow_edit" class="button_text hide" type="button" name="save_as_draft_allow_edit" value="Save" />');
        }


        var authToken = decodeURIComponent(getQueryString().authenticationToken);
        $('#save_as_draft_allow_edit').click(function (event, pageclick, btnidentity, navigatingpagno) {


            saveDraftValue = true;
            counter ? intimate_user_to_save(false, false) : null;
            $('#save_as_draft_submit_form').prop('disabled', true);
            if (!localStorage.getItem('automaticDraft') || localStorage.getItem('automaticDraft') == null) {
                $.postMessage({ saveAsDraftCall: true }, '*');
                $("#save_as_draft_submit_form").val('Saving');

            }
            matrix = [];

            $(".select").each(function () {
                var val = $(this).val();
                var id = $(this).attr("id");
                var find = findWithAttr(formElements, 'id', id);
                if (val != "AM" && val != "PM") {
                    if (find == -1) {

                        formElements.push({ "id": id, "value": val, "type": "select" });
                    } else {
                        formElements[find]['value'] = val;

                    }
                }

            });
            $(".multiple_choice input:not([type=hidden])").each(function () {
                var id = $(this).attr("name");
                var idss = $(this).attr("id");
                var val = $(this).val();

                if ($(this).is(":checked")) {
                    val = $(this).val();
                } else { val = ""; }
                var find = findWithAttr(formElements, 'id', id);

                if (idss.includes("_0")) {
                    if (!idsofOther.includes(idss)) {
                        if (idsofOther == "") {
                            idsofOther = idss;
                            formElements.push({ "id": id, "value": val, "type": "radio" });

                        } else
                            idsofOther = idsofOther + ',' + idss;

                    }
                }
                if (id.includes("_")) {
                    if (find == -1) {
                        if (val)
                            formElements.push({ "id": id, "value": val, "type": "radio" });

                    } else {
                        formElements[find]['value'] = val;

                    }

                }
            });
           
            var checkingflag = 1;
            $(".multiple_choice input:not([type=hidden])").each(function () {

                var id = $(this).attr("name");
                var val = $(this).val();

                if ($(this).is(":checked")) {

                    checkingflag = 0
                    val = $(this).val();
                    formElements.push({ "id": id, "value": val, "type": "radio" });
                } else {
                    if (checkingflag == 1) {
                        val = "";
                        formElements.push({ "id": id, "value": val, "type": "radio" });
                    }

                }


            });


            $(".matrix input[type=checkbox]").each(function () {
                var id = $(this).attr("name");
                var val;
                var find = findWithAttr(formElements, 'id', id);

                if ($(this).prop("checked") == true) {

                    var y = id.split("_");
                    val = y[y.length - 1];

                }
                else if ($(this).prop("checked") == false) {
                    val = 0;
                }
                if (find == -1) {
                    formElements.push({ "id": id, "value": val, "type": "checkbox" });

                } else {
                    for (var i = 0; i < formElements.length; i += 1) {
                        if (formElements[i]['id'] === id) {


                            formElements[i]['value'] = val;
                        }
                    }

                }


            })
            $(".checkboxes input:not([type=hidden])").each(function () {
                var val;
                if ($(this).attr("checked") == "checked") {

                    if (val == 0) {
                        val = 1;
                    }
                    val = 0;
                } else {

                    if (val == 1) {
                        val = 0;
                    }
                    val = 1;
                }
                if ($(this).prop("checked") == true) {
                    val = 1;
                }
                else if ($(this).prop("checked") == false) {
                    val = 0;
                }
                var id = $(this).attr("id");
                var find = findWithAttr(formElements, 'id', id);




                if (id.includes("_0")) {
                    if (!idsofOther.includes(id)) {
                        if (idsofOther == "")
                            idsofOther = id;
                        else
                            idsofOther = idsofOther + ',' + id;
                    }

                } else {
                    if (find == -1) {
                        if (val == 1 || val == 0)

                            formElements.push({ "id": id, "value": val, "type": "checkbox" });
                    } else {

                        formElements[find]['value'] = val;
                    }

                }


            })


            $(".matrix input[type='radio']:checked").each(function () {

                var id = $(this).attr("name");
                var idss = $(this).attr("id");
                var val = $(this).val();

                var find = findWithAttr(formElements, 'id', id);

                var findmatrix = findWithAttr(matrix, 'id', id);
                matrix.push({ "id": id, "value": val, "type": "radio" });


            });

            var ids = [];
            var clean = [];

            $.each(matrix, function (index, value) {
                if ($.inArray(value.id, ids) == -1) {
                    ids.push(value.id);
                    clean.push(value);
                } else {
                    clean[$.inArray(value.id, ids)]['value'] = value.value;
                }
            });



            formElements = formElements.concat(clean);


            if (idsofOther != "") {
                var arrayofother = idsofOther.split(",");
                arrayofother.forEach(function (item) {
                    var res = item.replace("_0", "_other");
                    var otherval = $("#" + res).val();
                    formElements.push({ "id": res, "value": otherval, "type": "textother" });
                });
            }
            localStorage.setItem('savedformElementsAuto', JSON.stringify([]));

            sessionStorage.setItem("saveAsDraft", "true");
            document.cookie = "saveAsDraft = " + "true";

            $('textarea').each(
                function () {
                    formElements.push({ "id": $(this).attr('id'), "value": $(this).val(), "type": "textarea" });

                }
            );

            $('form.appnitro input').each(function () {
                var input = $(this); // This is the jquery object of the input, do what you will

                if ($(this).attr('id') != undefined && $(this).attr("type") != "checkbox" && $(this).attr("type") != "radio" && $(this).attr("type") != "hidden" && $(this).attr("type") != "submit" && $(this).attr("type") != "button" && $(this).attr("type") != "file" && $(this).attr("type") != "image") {

                    var str = $(this).attr('id')
                    if (str.includes("_0") || str.includes("_other")) {

                        if (str.includes("_0")) {
                            var res = item.replace("_0", "");
                            var find = findWithAttr(formElements, 'id', res);
                            if (find == -1) {

                                formElements.push({ "id": res, "value": 0, "type": "othertext" });
                            }
                        }
                        var find = findWithAttr(formElements, 'id', str);
                        var otherval = $("#" + str).val();
                        if (find == -1) {

                            formElements.push({ "id": str, "value": otherval, "type": "othertext" });
                        }

                    } else {
                        if ($(this).parent().parent().parent().hasClass("date_field")) {
                            var iddate = $(this).parent().parent().parent().attr("id");
                            var iddatenn = iddate.replace("li", "");
                            var idsss = "element" + iddatenn;
                            var valuedate = $("#" + idsss + "_datepick").val();
                            var str = valuedate;
                            var myarray = str.split('/');
                            myarray[2] = $("#" + idsss + "_3").val();
                            myarray[1] = $("#" + idsss + "_2").val();
                            myarray[0] = $("#" + idsss + "_1").val();
                            valuedate = myarray[2] + "-" + myarray[0] + "-" + myarray[1];
                            var find = findWithAttr(formElements, 'id', idsss);
                            if (myarray[2] && myarray[0] && myarray[1]) { } else {
                                valuedate = "";
                            }

                            if (myarray[2] && myarray[0] && myarray[1]) {
                                formElements.push({ "id": idsss, "value": valuedate, "type": "date" });
                            } else {
                                valuedate = "";
                                formElements.push({ "id": idsss, "value": valuedate, "type": "date" });
                            }



                        } else {
                            if ($(this).parent().parent().parent().hasClass("phone")) {
                                var iddate = $(this).parent().parent().parent().attr("id");
                                var iddatenn = iddate.replace("li", "");
                                var idsss = "element" + iddatenn;
                                var first = $("#" + idsss + "_1").val();
                                var second = $("#" + idsss + "_2").val();
                                var third = $("#" + idsss + "_3").val();

                                var timeupdated = "";
                                var find = findWithAttr(formElements, 'id', idsss);
                                if (first && second && third) {
                                    timeupdated = first + second + third;
                                } else {
                                    timeupdated = "";
                                }
                                if (find == -1) {

                                    formElements.push({ "id": idsss, "value": timeupdated, "type": "phonr" });
                                } else {
                                    formElements[find]['value'] = timeupdated;
                                }
                            } else if ($(this).parent().parent().parent().hasClass("time_field")) {

                                var iddate = $(this).parent().parent().parent().attr("id");
                                var iddatenn = iddate.replace("li", "");
                                var idsss = "element" + iddatenn;
                                var hour = $("#" + idsss + "_1").val();
                                var min = $("#" + idsss + "_2").val();

                                var am = $("#" + idsss + "_4").val();
                                var timeupdated = timeConvertor('"' + hour + ':' + min + ':00' + am + '"');
                                timeupdated = hour + ':' + min + ':00';
                                if (am == "PM" && parseInt(hour) < 12) {
                                    hour = parseInt(hour) + parseInt(12);
                                    timeupdated = hour + ':' + min + ':00';
                                } else if (am == "PM" && parseInt(hour) == 12) {
                                    timeupdated = hour + ':' + min + ':00';
                                } else if (am == "AM" && parseInt(hour) == 12) {
                                    hour = parseInt(hour) - 12;
                                    hour=hour.toString();
                                    timeupdated = hour + ':' + min + ':00';
                                }
                                else {
                                    timeupdated = hour + ':' + min + ':00';
                                }
                                var find = findWithAttr(formElements, 'id', idsss);
                                if (hour && min) {
                                    timeupdated = timeupdated;
                                } else {
                                    timeupdated = null;
                                }
                                if (find == -1) {
                                    if (hour && min) {
                                        timeupdated = timeupdated;
                                    } else {
                                        timeupdated = null;
                                    }
                                    formElements.push({ "id": idsss, "value": timeupdated, "type": "time" });
                                } else {
                                    formElements[find]['value'] = timeupdated;
                                }
                            } else if ($(this).parent().parent().hasClass("price")) {
                                var idss = $(this).attr('id');
                                var splitname = idss.substr(idss.length - 2);
                                if (splitname == "_1") {


                                    var idssreplaced = idss.replace(new RegExp('_1' + '$'), '');
                                    var valdoller = $("#" + idssreplaced + "_1").val();

                                    var valcent = $("#" + idssreplaced + "_2").val();

                                    var valupdated = valdoller + "." + valcent;

                                    if (valdoller!='' || valcent!='') {

                                        if (valdoller != undefined && valcent != undefined) {

                                            var valupdated = valdoller + "." + valcent;
                                            if(valdoller && valcent) var valupdated = valdoller + "." + valcent;
                                            else if(valdoller && valcent=='') var valupdated = valdoller+'.0';
                                            else var valupdated = '0.'+valcent;



                                            formElements.push({ "id": idssreplaced, "value": valupdated, "type": "price" });

                                        }
                                    }

                                }


                            } else {
                                var find = findWithAttr(formElements, 'id', $(this).attr('id'));
                                if (find == -1) {
                                    formElements.push({ "id": $(this).attr('id'), "value": $(this).val(), "type": $(this).attr("type") });
                                } else {
                                    formElements[find]['value'] = $(this).val();
                                }
                            }


                        }

                    }


                }
            });

            $(".mf_sig_wrapper input").each(function () {
                var val = $(this).val();
                var id = $(this).attr("id");
                var find = findWithAttr(formElements, 'id', id);
                if (find == -1) {
                    formElements.push({ "id": id, "value": val, "type": "signature" });
                } else {
                    formElements[find]['value'] = val;
                }
            });


            formElements = formElements.concat(matrix);

            var cleanformElements = [];
            var idsformElements = [];
            $.each(formElements, function (index, value) {
             if(typeof value!=='undefined' && value!==null && typeof value.id!=='undefined' && value.id!==null &&  value.id.includes('_confirm')==false){
                if ($.inArray(value.id, idsformElements) == -1) {
                    idsformElements.push(value.id);
                    cleanformElements.push(value);
                } else {
                    cleanformElements[$.inArray(value.id, idsformElements)]['value'] = value.value;
                }
             }
            });

            serverBaseUrl = getQueryString().serverBaseUrl;

            if (!serverBaseUrl || serverBaseUrl == "undefined" || serverBaseUrl == undefined) {
                serverBaseUrl = localStorage.getItem('serverBaseUrlstored');


            } else if (serverBaseUrl.indexOf("machform/Upload")) {
                if (localStorage.getItem('serverBaseUrlstoredn') || localStorage.getItem('serverBaseUrlstoredn') == "undefined" || localStorage.getItem('serverBaseUrlstoredn') == undefined) {
                    if (!serverBaseUrl) {
                        serverBaseUrl = localStorage.getItem('serverBaseUrlstoredn');

                    }

                }

            }
            if (!formid || formid == "undefined" || formid == undefined) {
                formid = localStorage.getItem('formid');
            }
            if (!formid || formid == "undefined" || formid == undefined) {
                formid = localStorage.getItem('formidstoredn');
            }
            if (!tenantId || tenantId == "undefined" || tenantId == undefined) {
                tenantId = localStorage.getItem('tenantIdstoredn');
            }
            if (!senderId || senderId == "undefined" || senderId == undefined) {
                senderId = localStorage.getItem('senderIdstoredn');
            }
            if (!sentId || sentId == "undefined" || sentId == undefined) {
                sentId = localStorage.getItem('sentIdstoredn');
            }




            if (getQueryString().id) {
                formid = getQueryString().id;
            }
            var form = new FormData();

            form.append("formId", formid);
            form.append("tenant_id", tenantId);
            form.append("sender_id", senderId);
            form.append("recepient_id", recepientId);
            form.append("stafffacing", stafffacing);
            form.append("clientId", clientId);
            form.append("sentId", sentId);
            localStorage.setItem('normalFlow', formid);
            if (sentId && sentId != null && sentId != "null" && submissionidNew == 0) {
                if (sentId && sentId != null && sentId != "null" && submissionidNew == 0 && getQueryString().staffSubmissionId && getQueryString().staffSubmissionId != null && getQueryString().staffSubmissionId != "null" && getQueryString().staffSubmissionId != 0) {
                }
                else {
                    form.append("submissionId", 0);
                }

            } else {

                if (localStorage.getItem('submissionidNewstored') == 0) {
                    if (localStorage.getItem('ptidsubmissionidNewstored') != 0) {
                        form.append("submissionId", localStorage.getItem('ptidsubmissionidNewstored'));
                    }

                } else {
                    form.append("submissionId", localStorage.getItem('submissionidNewstored'));
                }

            }

            var total_page_count_check = $(".pagination-links").length;

            if (total_page_count_check == 0) {

                if (sentId && sentId != null && sentId != "null" && submissionidNew == 0 && getQueryString().staffSubmissionId && getQueryString().staffSubmissionId != null && getQueryString().staffSubmissionId != "null" && getQueryString().staffSubmissionId != 0) {
                    submissionidNew = getQueryString().staffSubmissionId;
                    form.append("submissionId", submissionidNew);
                }
            }
            form.append("confirmback", localStorage.getItem('confirm_back'));
            if (localStorage.getItem('ptidpractitionerid') != 0) {
                form.append("practitionerid", localStorage.getItem('ptidpractitionerid'));
            } else {
                form.append("practitionerid", practitionerid);
            }
            if ($(".appnitro").attr("automaticdraftsave") == 1) form.append("automaticdraftsave", 1);
            form.append("enableCollaborateEdit", localStorage.getItem('enableCollaborateEdit'));
            form.append("formData", JSON.stringify(cleanformElements));


            if ($(".confirmed_elements").length) {
                var x = [];
                $(".confirmed_elements").each(function () {
                    x.push($(this).val());
                });
                form.append('confirmed_elements', x);
            }
            if ($(".not_confirmed_class").length) {
                var y = [];
                $(".not_confirmed_class").each(function () {
                    y.push($(this).val());
                });
                form.append("not_confirmed_elements", y);
            }


            if (localStorage.getItem("numberfields") && localStorage.getItem("numberfields") !== null && localStorage.getItem("numberfields").length) {
                form.append("number_fields", localStorage.getItem("numberfields"));
            }

            if (localStorage.getItem("numberfieldsMoney") && localStorage.getItem("numberfieldsMoney") !== null && localStorage.getItem("numberfieldsMoney").length) {
                form.append("number_fields_money", localStorage.getItem("numberfieldsMoney"));

            }

            if ($(".singlefile:visible").length) {

                var files = [];
                $(".singlefile:visible").each(function () {
                    var element_id = $(this).attr("id");
                    if (document.getElementById(element_id).files.length) {
                        files.push(element_id);
                        form.append("file[]", $('#' + element_id).prop('files')[0]);
                    }
                });

                form.append('filIds', files);
            }

            if ($(".valueChangedElement").length) {
                var x = [];
                $(".valueChangedElement").each(function () {
                    var element_id = $(this).attr("id").split("_");
                    if (element_id.length && element_id[1]) x.push(element_id[1]);
                });
                form.append("changed_elements", x);
            }

            var serverBaseUrlN = serverBaseUrl.replace("%3A%2F%2F", "://");
            var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
            var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");


            if (getQueryString().uniqueFormIdentity) {
                form.append("uniqueFormIdentity", getQueryString().uniqueFormIdentity);
            }
            if (getQueryString().draftSave && getQueryString().draftSave == 'true') {
                form.append("draftSave", true);
            }
            if (localStorage.getItem('automatic') && localStorage.getItem('automatic') == 1) {
                localStorage.removeItem('automatic');
                form.append("automatic", true);
            }


            var formSendMode = getQueryString().formSendMode;

            if (localStorage.getItem("formMode_"+uniQueFormIdentity) != null && localStorage.getItem("formMode_"+uniQueFormIdentity) != "null") {
                let formModeValue = localStorage.getItem("formMode_"+uniQueFormIdentity);
                if(formModeValue == 'appless'){
                    form.append('applessMode', 1);
                }else{
                    form.append('applessMode', 0);
                }
            }else{
                if (typeof (formSendMode) == 'undefined' || formSendMode != 'appless') {
                    form.append('applessMode', 0);
                } else if (formSendMode == 'appless') {
                    form.append('applessMode', 1);
                } else {
                    form.append('applessMode', 0);
                }
            }
            if (localStorage.getItem('automaticDraft') && localStorage.getItem('automaticDraft') !== null && typeof localStorage.getItem('automaticDraft') !== 'undefined' && localStorage.getItem('automaticDraft') == 1) {
                form.append('automaticDraft', 1);
            }
            if (getQueryString().uniqueFormIdentity) {
                form.append("uniqueFormIdentity", getQueryString().uniqueFormIdentity);
            }
             // session unique in multiple tabs checking
             if (getQueryString()) {
                let appendUrl = appendBaseUrl(serverBaseUrl);
                serverBaseUrlN = appendUrl;
                var jsonarray = JSON.stringify(getQueryString());
                var jsonscript = JSON.parse(jsonarray);
                jsonscript['serverBaseUrl'] = appendUrl;
                form.append("request_params", JSON.stringify(jsonscript));
            }
            var authToken = decodeURIComponent(getQueryString().authenticationToken);
            // session unique in multiple tabs checking
            $(".appnitro input").each(function(){
                if($(this).attr('type')=='radio' && $(this).is(':checked')){
                    $(this).attr('checked','checked');
                }else if($(this).attr('type')=='checkbox' && $(this).is(':checked')){
                    $(this).attr('checked','checked');
                }else{
                    if($(this).val()) $(this).attr('value',$(this).val());
                } 
            });
            $(".appnitro textarea").each(function(){
                if($(this).attr('id') && $(this).val()) document.getElementById($(this).attr('id')).innerHTML = $(this).val();
            });
            $(".appnitro select").each(function(){
                if($(this).attr('id') && $(this).val()) $('#'+$(this).attr('id')+' option[value="'+$(this).val()+'"]').attr('selected','selected');
            });
            var html=document.documentElement.innerHTML;
            if(typeof html!=="undefined" && html){
                html=stripScripts(html);
                html=html.replace(/\r?\n|\r/g, "");
                html=html.replace(/\t/g,'');
                html=html.replace(/<!--[\s\S]*?-->/g,'');
                //form.append("bodyHtmlContent",JSON.stringify({'bodyHtml':html}));
            }
            if($('input[name=page_number]').length) form.append("page_number",$('input[name=page_number]').val());
            if (getQueryString().savedDraftid && getQueryString().savedDraftid !== null && getQueryString().savedDraftid != 'undefined' && getQueryString().savedDraftid > 0 && (!getQueryString().AllowEdit || getQueryString().AllowEdit == false || getQueryString().AllowEdit == 'false')) {
                form.append("savedDraftid",getQueryString().savedDraftid);
            }
            if(getQueryString().staffSubmissionId && typeof getQueryString().staffSubmissionId !== "undefined" && getQueryString().staffSubmissionId != null && getQueryString().staffSubmissionId != "null" && getQueryString().staffSubmissionId != 0){
                form.append("staffSubmissionId",getQueryString().staffSubmissionId);
            }

            var total_page_count_check = $(".pagination-links").length;
            if (total_page_count_check > 0) {
                if (btnidentity == 'primary') {

                    var active_page = parseInt($(".ap_tp_num_active").text());
                    var total_page_count_check = $(".pagination-links").length;
                    if (active_page == total_page_count_check) {
                        var newPageNumber = active_page;
                    } else {
                        var newPageNumber = active_page + 1;
                    }
                    localStorage.setItem('navigatedpages', active_page + ' to ' + newPageNumber);
                } else if (btnidentity == 'secondary') {

                } else if (btnidentity == 'navigation') {
                    var active_page = parseInt($(".ap_tp_num_active").text());
                    localStorage.setItem('navigatedpages', active_page + ' to ' + navigatingpagno);
                }

                if (localStorage.getItem('navigatedpages')) {
                    form.append("pagesnavigated", localStorage.getItem('navigatedpages'));
                }
            }else {
                if (localStorage.getItem('navigatedpages')) {
                    form.append("pagesnavigated", 0);
                }
            }
            
            if(getQueryString().FormEntryID && typeof getQueryString().FormEntryID !== "undefined" && getQueryString().FormEntryID != null && getQueryString().FormEntryID != "null" && getQueryString().FormEntryID != 0){
                form.append("allowEdit",true);
                form.append("FormEntryID",getQueryString().FormEntryID);
            }
           
            if($('#eSignatureLogsValues').length){
                if($('#eSignatureLogsValues').val()!='' && $('#eSignatureLogsValues').val()){
                    form.append("eSignatureLogs",$('#eSignatureLogsValues').val()); 
                }
            }
            if($('#allowEditSendId').length && $('#allowEditSendId').val()){
                form.append("sentId",$('#allowEditSendId').val());
            }
            if(getQueryString().create_send && typeof getQueryString().create_send !== "undefined" && getQueryString().create_send != null && getQueryString().create_send != "null" && getQueryString().create_send != 0){
                form.append("createSendMode",1);// to know api is in draft mode
            }
            if($("#completed-forms-recipients").length){
                form.append("completedFormsRecipients", document.getElementById("completed-forms-recipients").value);
                form.append("completedFormsRecipientsStorage", !localStorage.getItem('completedFormsRecipientsStorage') ? '' : localStorage.getItem('completedFormsRecipientsStorage'));
                localStorage.setItem("completedFormsRecipientsStorage", document.getElementById("completed-forms-recipients").value);
            }
            var serverBaseUrlN = serverBaseUrl.replace("%3A%2F%2F", "://");
            var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
            var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
            form.append('curlUrl',serverBaseUrlN + "/cometchat/citus-health/v4/save-as-draft-details.php");
            
            //if($("input[name='file_upload_field[]']").length && $(".file_queue div").length) form.append("advanced_file_upload_fields",$("input[name='file_upload_field[]']").map(function(){return $(this).val();}).get());
            var fileFields=[];
            $('.file_queue').each(function( index ) {
            if($(this).children('img').length || $(this).find(".completed").length || $(this).find(".complete").length){
            var fileId=$(this).closest('li').attr('id');
                if(typeof fileId!=='undefined' && fileId!=null && fileId) var Id= fileId.split('_'); 
                if(typeof Id[1]!=='undefined' && Id[1]!=null && Id[1] && $('.file-element-'+Id[1]).length) fileFields.push($('.file-element-'+Id[1]).val());
            }    
            });
            if(fileFields.length && !bStaffChangeValidation) form.append("advanced_file_upload_fields",fileFields.join(','));
            var settings = {
                "async": true,
                "crossDomain": true,
                "url": "CorsHttpRequestProxy.php",
                "method": "POST",
                "headers": {
                    "cache-control": "no-cache",
                    "Access-Control-Allow-Origin": '*',
                    "authentication-token": decodeURIComponent(authToken)
                },
                "processData": false,
                "contentType": false,
                "timeout": 180000,
                "mimeType": "multipart/form-data",
                "data": form
            }
            var fail=function(){
                draftFail = 1;
                checkonline();
            }               
            $.ajax(settings).done(function (response) {
                if($(".loaderImg").length) $(".loaderImg").remove();
                if($(".loader-image-div").length) $(".loader-image-div").remove(); 
                var responsesubid = JSON.parse(response);
                if(typeof responsesubid === 'object' && responsesubid !== null && responsesubid.hasOwnProperty('code') && responsesubid.code==401){
                    draftFail = 1;
                    
                        setTimeout(function () { $(".swal-modal").css("vertical-align", "top");$(".swal-modal").css("margin-top", "18mm"); });
                        $.postMessage({ internetConnectionerror: true }, '*');
                        swal({
                           text: "Internal server error occurred and not able to save the Draft. Please go back to Drafts bucket and access the Draft Form again",
                           button: false
                        }).then(function(isConfirm){
                            if(isConfirm){
                               if($('#submit_form1').length) $('#submit_form1').prop('disabled',false); 
                               if($('#submit_primary1').length) $('#submit_primary1').prop('disabled',false);            
                           
                            }
                        });
                    return false;
                }
                if(typeof responsesubid === 'object' && responsesubid !== null && responsesubid.hasOwnProperty('status') && responsesubid.status==false){
                    draftFail = 1;
                    if (typeof(responsesubid.code) !== 'undefined' && responsesubid.code) {
                        var returnErrorData = {};
                        // error code handling
                        if(errorCodesDisplay.indexOf(responsesubid.code) > -1){
                            $.postMessage({ formCorruptionError: true }, '*');
                            returnErrorData = errorCodeHandling(responsesubid.code);
                            var popTitle = returnErrorData.popTitle;
                            var iconType = returnErrorData.iconType;
                            var textmsg = returnErrorData.message
                            
                            swal({
                                title: popTitle,
                                text: textmsg,
                                icon: iconType,
                                showConfirmButton: false,
                                allowOutsideClick: false,
                                closeOnClickOutside: false,
                                buttons: 'OK',
                            }).then(function (isConfirm) {
                                // make send iframe button to enable state
                                if (isConfirm && iconType =='error') {
                                    if($('#submit_primary1').length) $('#submit_primary1').prop('disabled',false);
                                    if($('#submit_form1').length) $('#submit_form1').prop('disabled',false);
                                    if($('#review_submit').length) $('#review_submit').prop('disabled',false);
                                    if($('#submit_secondary1').length) $('#submit_secondary1').prop('disabled', false);
                                }
                            });
                        }
                    }
                    checkonline();
                    return false;
                }
                //save as draft msg
                draftFail = 0;
                $('#eSignatureLogsValues').val('');
                if (btnidentity == 'primary') {
                    $("#submit_primary").trigger('click');
                } else if (btnidentity == 'secondary') {
                    $("#submit_secondary").trigger('click')
                } else if (btnidentity == 'navigation') {
                    click_link_pagination(navigatingpagno);
                } else if (btnidentity == 'submit_form') {
                    $("#submit_form").trigger('click')
                }
                //save as draft msg
                if (!localStorage.getItem('automaticDraft') || localStorage.getItem('automaticDraft') == null) {
                    $.postMessage({ saveAsDraftCallCompleted: true }, '*');
                }
                localStorage.setItem("draftsuccess", 1);
                localStorage.removeItem('automaticDraft');

                


                submissionidNew = responsesubid.submission_id;
                localStorage.setItem("fileSaveDraftId", submissionidNew);

                localStorage.setItem('submissionidNewstored', responsesubid.submission_id);
                localStorage.setItem('ptidsubmissionidNewstored', localStorage.getItem('submissionidNewstored'));
                formName = responsesubid.form_name;
                $('#save_as_draft_submit_form').prop('disabled', false);
                $('#save_as_draft_submit_form').val("Save As Draft");
                $.postMessage({ saveasdraftidtodeleted: submissionidNew }, '*');
                $.postMessage({ autosavecalled: false }, '*');
                $.postMessage({ autosavecalledformid: formid }, '*');
                checkonline();

            }).fail(function (jqXHR, textStatus, errorThrown) {

                draftFail = 1;
                checkonline();
                
            });
        })

        $(".element,.matrix input,.mf_sig_wrapper input").blur(function () {
            if ($(this).hasClass("radio")) {
                var elem_id = $(this).attr('name');

            } else {
                var elem_id = $(this).attr("id");
            }
            if (localStorage.getItem('datapopulatefromsubmission') != "") {

                checkJson = IsValidJSONString(localStorage.getItem('datapopulatefromsubmission'));


                if (checkJson == true) {
                    var response = jQuery.parseJSON(localStorage.getItem('datapopulatefromsubmission'));
                    if (response && response['results'] && typeof response['results'] === 'object' && response['results'] !== null && response['results'].hasOwnProperty(elem_id)) delete response['results'][elem_id];
                    localStorage.setItem("datapopulatefromsubmission", JSON.stringify(response));
                }
            }

        });


        if (getParameterByName('senderFielddisabled') && getParameterByName('senderFielddisabled') != "null" && getParameterByName('senderFielddisabled') != null) {

            $(".disable_prefill_edit .mf_sig_wrapper").css("pointer-events", "none");
            $(".disable_prefill_edit .mf_sigpad_clear").addClass('hide');
            $(".disable_prefill_edit select").each(function () {
                if ($(this).val() != "") {

                    var id = $(this).parents('.disable_prefill_edit').attr('id');
                    if ($('#' + id).hasClass("time_field")) {
                        if ($('#' + id + " input").val() != "") {
                            $('#' + id).on('click', function (event) {
                                event.preventDefault();
                            });
                            $('#' + id).css("pointer-events", "none");
                        }
                    } else {
                        $('#' + id).on('click', function (event) {
                            event.preventDefault();
                        });
                        $('#' + id).css("pointer-events", "none");
                    }

                }
            });

            $(".disable_prefill_edit textarea").each(function () {
                if ($(this).val() != "") {
                    $(this).prop('readonly', true);
                }
            });
            $(".disable_prefill_edit input").each(function () {
                if (($(this).val() != "") && ($(this).attr('type') == "text" || $(this).attr('type') == "hidden")) {

                    var id = $(this).parents('.disable_prefill_edit').attr('id');
                    if (!$('#' + id).hasClass("time_field")) {


                        if ($(this).val() != "http://") {
                            $('#' + id).on('click', function (event) {
                                event.preventDefault();
                            });
                            $(this).prop('readonly', true);
                            $('#' + id).css("pointer-events", "none");
                            $(".disable_prefill_edit .datepicker").addClass('hide');
                        }

                    }
                }

            });
            $('.disable_prefill_edit input[type="checkbox"]').each(function () {
                if ($(this).prop("checked") == true && $(this).attr('type') == "checkbox") {
                    var id = $(this).parents('.disable_prefill_edit').attr('id');
                    $('#' + id).on('click', function (event) {
                        event.preventDefault();
                    });
                    $(this).prop('readonly', true);

                    $('#' + id).css("pointer-events", "none");



                }

            });
            $('.disable_prefill_edit input.radio').each(function () {
                if ($(this).prop("checked") && $(this).attr('type') == "radio") {
                    var id = $(this).parents('.disable_prefill_edit').attr('id');
                    $('#' + id).on('click', function (event) {
                        event.preventDefault();
                    });
                    $(this).prop('readonly', true);

                    $('#' + id).css("pointer-events", "none");

                }

            });

            $('.disable_prefill_edit input').each(function () {
                if ($(this).prop("checked") && $(this).attr('type') == "radio") {
                    var id = $(this).parents('.disable_prefill_edit').attr('id');
                    $('#' + id).on('click', function (event) {
                        event.preventDefault();
                    });
                    $(this).prop('readonly', true);

                    $('#' + id).css("pointer-events", "none");

                }

            });





        }

        if (getQueryString().fromMob == 'true' || getQueryString().fromMob == true) {
            if (getQueryString().sentId && getQueryString().sentId != null && getQueryString().sentId != 'null' && getQueryString().sentId != 'undefined') {
                $(".manage-role-btn").hide();

            }
        }
        else {


            if ($('form').find('div input[type=text],textarea,select').filter(':first').hasClass("other")) {


                setTimeout(function () {
                    $('form').find('div textarea').filter(':first').closest('.highlighted').removeClass("highlighted");

                }, 1000);

            }

            setTimeout(function () {
                //$('form').find('input[type=text],textarea,select').filter(':not(.other):visible:first').trigger("click");

                $('li').removeClass("highlighted");

            }, 3000);
        }



        var staffFacing = getQueryString().staffFacing;
        var prepopulate = getQueryString().populatePreviousSubmission;
        var draftPopulate = getQueryString().draftPopulate;
        var confirmFillAction = getQueryString().confirmActionPrefill;
        var checkConfirmDraft = true;
        if (typeof draftPopulate !== "undefined") {
            prepopulate = draftPopulate;
        }
        if (getQueryString().savedDraftid && getQueryString().savedDraftid > 0 && getQueryString().AllowEdit && (getQueryString().AllowEdit == true || getQueryString().AllowEdit == 'true')) {
            checkConfirmDraft = false;

        }
        var delay=1000;
        setTimeout(function(){
            if (checkConfirmDraft == true && staffFacing && (staffFacing == true || staffFacing == 'true') && prepopulate && (prepopulate == true || prepopulate == 'true') && confirmFillAction && (confirmFillAction == true || confirmFillAction == 'true') && $(".pre_populate_confirm").length) {
                /******prefill confirm********/
                /********Draft from  editting case***********/
                var serverBaseUrl = getQueryString().serverBaseUrl;
                var serverBaseUrlN = serverBaseUrl.replace("%3A%2F%2F", "://");
                var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
                var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");



                if (getQueryString().savedDraftid && getQueryString().savedDraftid > 0) {
                    var submission_id = getQueryString().savedDraftid;
                }else if(localStorage.getItem('submissionidNewstored')!==null){
                    var submission_id = localStorage.getItem('submissionidNewstored');
                }else{
                    var submission_id = 0;
                }
                var formId = getQueryString().id ? getQueryString().id : getQueryString().formId;
                var formUniqueId = getQueryString().uniqueFormIdentity;
                var authToken = decodeURIComponent(getQueryString().authenticationToken);
                getData(serverBaseUrlN, submission_id, formId, formUniqueId, authToken, function (response) {

                    var response = JSON.parse(response);
                    if(localStorage.getItem("initialLoad") !== null && localStorage.getItem("initialLoad")==formUniqueId){
                        delay=10;
                    }else{
                        localStorage.setItem("initialLoad",formUniqueId);
                    }
                    $('input[name=form_id]').after('<input type="hidden" id="confirm_pages" value="' + response.pages + '">');
                    $('input[name=form_id]').after('<input type="hidden" id="confirm_hidden_elems" value="' + response.elems + '">');
                    $('input[name=form_id]').after('<input type="hidden" id="not_confirm_hidden_elems" value="' + response.elems_not_confirmed + '">');
                    $('input[name=form_id]').after('<input type="hidden" id="value_changed_elems" value="' + response.elems_changed + '">');

                    /************Iterate through elements ****************************************/
                    $(".element").each(function () {

                        var ele_id = $(this).attr("id");
                        var ele_type = $(this).prop('type');
                        if (ele_id && ele_type != 'file') {
                            var id = ele_id.split("_")[1];
                            var class_s = $("#li_" + id).attr('class');
                            /**************Check for data********************* */
                            var hasData = false;
                            if ($("#li_" + id).hasClass("simple_name")) {

                                if ($("#element_" + id + "_1").val() != '' || $("#element_" + id + "_2").val() != '') hasData = true;
                            } else if ($("#li_" + id).hasClass("fullname")) {
                                if ($("#element_" + id + "_1").val() != '' || $("#element_" + id + "_2").val() != '' || $("#element_" + id + "_3").val() != '' || $("#element_" + id + "_4").val() != '') hasData = true;

                            } else if ($("#li_" + id).hasClass("simple_name_wmiddle")) {
                                if ($("#element_" + id + "_1").val() != '' || $("#element_" + id + "_2").val() != '' || $("#element_" + id + "_3").val() != '') hasData = true;
                            } else if ($("#li_" + id).hasClass("fullname_wmiddle")) {
                                if ($("#element_" + id + "_1").val() != '' || $("#element_" + id + "_2").val() != '' || $("#element_" + id + "_3").val() != '' || $("#element_" + id + "_4").val() != '' || $("#element_" + id + "_5").val() != '') hasData = true;
                            } else if ($("#li_" + id).hasClass("date_field")) {
                                if ($("#element_" + id + "_1").val() != '' || $("#element_" + id + "_2").val() != '' || $("#element_" + id + "_3").val() != '') hasData = true;
                            } else if ($("#li_" + id).hasClass("dropdown")) {
                                if ($("#element_" + id).val() != '' && $("#element_" + id).val() !=null) hasData = true;
                            } else if ($("#li_" + id).hasClass("phone")) {
                                if ($("#element_" + id + "_1").val() != '' || $("#element_" + id + "_2").val() != '' || $("#element_" + id + "_3").val() != '') hasData = true;
                            } else if ($("#li_" + id).hasClass("checkboxes")) {
                                $('input[id^="element_' + id + '_"]').each(function () {
                                    if ($(this).is(":checked")) hasData = true;
                                });
                            } else if ($("#li_" + id).hasClass("multiple_choice")) {
                                if ($('input[name="element_' + id + '"]').is(':checked')) hasData = true;
                            } else if ($("#li_" + id).hasClass("address")) {
                                if ($("#element_" + id + "_1").val() != '' || $("#element_" + id + "_2").val() != '' || $("#element_" + id + "_3").val() != '' || $("#element_" + id + "_4").val() != '' || $("#element_" + id + "_5").val() != '' || $("#element_" + id + "_6").val() != '') hasData = true;

                            } else if ($("#li_" + id).hasClass("time_field")) {
                                if ($("#element_" + id + "_1").val() != '' || $("#element_" + id + "_2").val() != '') hasData = true;

                            } else if ($("#li_" + id).hasClass("price")) {
                                if ($("#element_" + id + "_1").val() != '' || $("#element_" + id + "_2").val() != '' || (typeof $("#element_" + id + "_2").attr('placeholder')!=='undefined' && $("#element_" + id + "_2").attr('placeholder') != '') || (typeof $("#element_" + id + "_1").attr('placeholder') !== 'undefined' && $("#element_" + id + "_1").attr('placeholder') != '')) hasData = true;

                            } else {

                                if ($("#element_" + id).val() != '' && $("#element_" + id).val() != 'http://' && $("#element_" + id).val() != '[]') {
                                    hasData = true;

                                }


                            }
                            var page_num = $('input[name=page_number]').val();
                            var confirm_pages_hidden = $("#confirm_pages").val() != '' ? $("#confirm_pages").val().split(',') : [];
                            var confrim_hidden_elems = $("#confirm_hidden_elems").val() != '' ? $("#confirm_hidden_elems").val().split(',') : [];
                            var not_confrim_hidden_elems = $("#not_confirm_hidden_elems").val() != '' ? $("#not_confirm_hidden_elems").val().split(',') : [];
                            var value_changed_elems = $("#value_changed_elems").val() != '' ? $("#value_changed_elems").val().split(',') : [];
                            if (not_confrim_hidden_elems && not_confrim_hidden_elems.indexOf(id) !== -1) {
                                var show_strict = true;
                            } else {
                                var show_strict = false;
                            }
                            if (value_changed_elems.length && value_changed_elems.indexOf(id) !== -1) {
                                var valueChanged = true;
                                if ($("#li_" + id).hasClass("valueChangedElement") != true) $("#li_" + id).addClass("valueChangedElement");
                                if ($("#element_changed_" + id).length == 0) $("#li_" + id).append("<input type='hidden' id='element_changed_" + id + "' name='element_changed_" + id + "' class='element_changed_class' value='" + id + "'>");
                            } else {
                                var valueChanged = false;
                            }
                            var FromDRaft = (getQueryString().savedDraftid && getQueryString().savedDraftid > 0 && !getQueryString().AllowEdit) ? true : false;
                            var createSend = (getQueryString().create_send == true ||  getQueryString().create_send == 'true') ? true : false;
                            var fromMobSend = (getQueryString().fromMob == 'true' || getQueryString().fromMob == true) ? true : false;
                            if (FromDRaft == true && show_strict == true) {
                                var show_confrim_action = true;
                            } else if (FromDRaft == true && (createSend == false) && show_strict != true) {
                                var show_confrim_action = false;
                            } else {
                                var show_confrim_action = true;
                            }
                            if (fromMobSend == true){
                                var show_confrim_action = true;
                            }
                            if (page_num && confirm_pages_hidden.length && confirm_pages_hidden.indexOf(page_num) !== -1 && show_strict == false) var initial_load_page = false; else var initial_load_page = true;
                            if (confrim_hidden_elems.length && confrim_hidden_elems.indexOf(id) !== -1) var already_confirmed = true; else var already_confirmed = false;
                            /******Data checking ends here...*******/
                            i
                            if (show_confrim_action == true && initial_load_page == true && already_confirmed != true && typeof class_s !== 'undefined' && class_s.includes("pre_populate_confirm") == true && ($("#li_" + id).hasClass("confirmprefill") != true && $("#confirm_link_" + id).length == 0) && hasData == true && valueChanged != true) {
                                $("#li_" + id).find(".description").append('<a  href="javascript:void(0)" data-id="' + id + '" id="confirm_link_' + id + '" style="padding-left:15px;color:blue;" class="confirm_link">Confirm</a>');
                                $("#li_" + id).addClass("confirmprefill");
                                $("#li_" + id).append("<input type='hidden' id='element_not_confirmed_" + id + "' name='element_not_confirmed_" + id + "' class='not_confirmed_class' value='" + id + "'>");
                            }
                            if (already_confirmed == true && $("#checked_element_" + id).length == 0 && valueChanged != true) {
                                $("#li_" + id).find(".description").append("<i class='icon-checkmark' style='color:green;margin-left:10px;'></i><input type='hidden' name='checked_element_" + id + "' value='" + id + "' class='confirmed_elements' id='checked_element_" + id + "'>");

                            }
                        }

                    });
                    $(".pre_populate_confirm input").change(function () {
                        if($(this).hasClass('radio') && !$(this).hasClass('focused')) return; 
                        var clickedelementParent = $(this).closest('.pre_populate_confirm').attr("id");
                        if (clickedelementParent) var id = clickedelementParent.split("_")[1]; else var id = null;
                        if ($("#" + clickedelementParent + " .confirm_link").length) {
    
                            $("#" + clickedelementParent + " .confirm_link").remove();
                            $("#" + clickedelementParent + " .not_confirmed_class").remove();
                            $("#" + clickedelementParent).css("border", "none");
                            $("#" + clickedelementParent + " .confirm_error_present").remove();
                        }
                        $("#" + clickedelementParent).removeClass("confirmprefill");
                        $("#" + clickedelementParent).addClass("valueChangedElement");
                        $("#" + clickedelementParent).append("<input type='hidden' id='element_changed_" + id + "' name='element_changed_" + id + "' class='element_changed_class' value='" + id + "'>");
                        if($(".confirm_error_present").length==0){
                            enableSubmitButton();
                        }
    
                    })
                    $(".pre_populate_confirm select").change(function () {
                        var clickedelementParent = $(this).closest('.pre_populate_confirm').attr("id");
                        if (clickedelementParent) var id = clickedelementParent.split("_")[1]; else var id = null;
                        if ($("#" + clickedelementParent + " .confirm_link").length) {
    
                            $("#" + clickedelementParent + " .confirm_link").remove();
                            $("#" + clickedelementParent + " .not_confirmed_class").remove();
                            $("#" + clickedelementParent).css("border", "none");
                            $("#" + clickedelementParent + " .confirm_error_present").remove();
                        }
                        $("#" + clickedelementParent).removeClass("confirmprefill");
                        $("#" + clickedelementParent).addClass("valueChangedElement");
                        $("#" + clickedelementParent).append("<input type='hidden' id='element_changed_" + id + "' name='element_changed_" + id + "' class='element_changed_class' value='" + id + "'>");
                        if($(".confirm_error_present").length==0){
                            enableSubmitButton();
                        }
    
                    })
                    $(".pre_populate_confirm textarea").change(function () {
                        var clickedelementParent = $(this).closest('.pre_populate_confirm').attr("id");
                        if (clickedelementParent) var id = clickedelementParent.split("_")[1]; else var id = null;
                        if ($("#" + clickedelementParent + " .confirm_link").length) {
    
                            $("#" + clickedelementParent + " .confirm_link").remove();
                            $("#" + clickedelementParent + " .not_confirmed_class").remove();
                            $("#" + clickedelementParent).css("border", "none");
                            $("#" + clickedelementParent + " .confirm_error_present").remove();
    
                        }
                        $("#" + clickedelementParent).removeClass("confirmprefill");
                        $("#" + clickedelementParent).addClass("valueChangedElement");
                        $("#" + clickedelementParent).append("<input type='hidden' id='element_changed_" + id + "' name='element_changed_" + id + "' class='element_changed_class' value='" + id + "'>");
                        if($(".confirm_error_present").length==0){
                            enableSubmitButton();
                        }
                    })

                });
                function enableSubmitButton(){
                    
                        $('input:hidden[name=submit_primary]:not([type=submit])').remove();
                        $("#send_button_value").remove();
                        $('#submit_secondary1').prop('disabled', false);
                        $('.pagination-links').css("pointer-events",'auto');
                        if($('#submit_form1').length) $('#submit_form1').prop('disabled',false);
                        if($('#submit_primary1').length) $('#submit_primary1').prop('disabled',false);
                    
                }
                function getData(serverBaseUrlN, submission_id, formId, formUniqueId, authToken, callback) {
                    $.ajax({
                        type: "POST", async: false, crossDomain: true, headers: { "cache-control": "no-cache", "Authentication-Token": decodeURIComponent(authToken), "Access-Control-Allow-Origin": '*' },
                        url: 'CorsHttpRequestProxy.php',
                        data: { formId: formId, submissionId: submission_id, FormUniqueId: formUniqueId, formId: formId,curlUrl: serverBaseUrlN + "/cometchat/citus-health/v4/get-confirmed-elements.php"},
                        success: callback
                    });
                }

                /**************************************************/
                $(".confirm_link").click(function () {
                    var id = $(this).data('id');
                    if ($("#li_" + id).hasClass("confirmprefill") == true) {
                        $("#element_not_confirmed_" + id).remove();
                        $("#li_" + id).removeClass("confirmprefill");
                        $(this).after("<i class='icon-checkmark' style='color:green;margin-left:10px;'></i><input type='hidden' name='checked_element_" + id + "' value='" + id + "' class='confirmed_elements' id='checked_element_" + id + "'>");
                        $(this).remove();
                        $("#confirm_error_" + id).remove();
                        $("#li_" + id).css("border", "none");

                    }
                    if($(".confirm_error_present").length==0){
                        $('input:hidden[name=submit_primary]:not([type=submit])').remove();
                        $("#send_button_value").remove();
                        $('#submit_secondary1').prop('disabled', false);
                        $('.pagination-links').css("pointer-events",'auto');
                        if($('#submit_form1').length) $('#submit_form1').prop('disabled',false);
                        if($('#submit_primary1').length) $('#submit_primary1').prop('disabled',false);
                    }
                });
            }
        },delay);
        /********************************* */

        var current_url = window.location.href;
        var queryStringKeyValue = current_url.replace('?', '').split('&');
        var qsJsonObject = {};
        for (i = 0; i < queryStringKeyValue.length; i++) {
            qsJsonObject[queryStringKeyValue[i].split('=')[0]] = queryStringKeyValue[i].split('=')[1];
        }
        if (qsJsonObject.clearForm && qsJsonObject.clearForm == 1 && localStorage.getItem("pageNavigation")) localStorage.removeItem("pageNavigation");


        if (!localStorage.getItem("formUniqueID") || typeof localStorage.getItem("formUniqueID") === 'undefined' || localStorage.getItem("formUniqueID") != qsJsonObject.uniqueFormIdentity) {
            localStorage.removeItem("pageNavigation");
        }
        if ($("li#error_message").length || $(".confirm_error_present").length) {

            var error_present = true;
        } else {
            var error_present = false;
        }
        var curren_navigation_array = localStorage.getItem("pageNavigation") ? JSON.parse(localStorage.getItem("pageNavigation")) : false;


        var active_page = parseInt($(".ap_tp_num_active").text());

        if (curren_navigation_array != false && curren_navigation_array.length == 0) localStorage.removeItem("pageNavigation");
        if (error_present == true && curren_navigation_array != false) {
            localStorage.removeItem("pageNavigation");
        } else if (error_present == false && curren_navigation_array != false && curren_navigation_array.length > 0) {
            var index = curren_navigation_array.indexOf(active_page);
            if (index > -1) curren_navigation_array.splice(index, 1);
            if (curren_navigation_array.length) {
                $('#pagination_header').click(false);
                $('#pagination_header').append("<img src='images/my-mach-loader.gif' style='left: 35%;position: absolute;top: -61%;' id='pagination_loading'>");
                localStorage.setItem("pageNavigation", JSON.stringify(curren_navigation_array));
                $("#submit_primary").trigger("click");

            } else {
                localStorage.removeItem("pageNavigation");
            }

        }
    });
    $(".pagination-links").css("cursor", "pointer");
    $(".pagination-links").click(function (e) {
        e.preventDefault();
        localStorage.setItem('automatic', 1);
        localStorage.setItem("automaticDraft", 1);
        let newpage_no = parseInt($(this).find(".ap_tp_num").text());
        if ((window.location.href.indexOf("/view.php") > -1) || (loadformType == 'worklist')) {
            click_link_pagination(newpage_no);
        } else {
            if (AllowEdit == 'true' || AllowEdit == true) {
                $("#save_as_draft_allow_edit").trigger('click', [1, 'navigation', newpage_no]);
            } else {
                $("#save_as_draft_submit_form").trigger('click', [1, 'navigation', newpage_no]);
            }
        }
    });

    function click_link_pagination(newPageNumber) {

        localStorage.setItem("pagenavigationtopclick", 1);
        var draftEditing = false;
        if (getQueryString().staffSubmissionId && getQueryString().staffSubmissionId !== null && getQueryString().staffSubmissionId != 'undefined' && getQueryString().staffSubmissionId > 0) {
            draftEditing = true;
        }
        if (getQueryString().savedDraftid && getQueryString().savedDraftid !== null && getQueryString().savedDraftid != 'undefined' && getQueryString().savedDraftid > 0 && (!getQueryString().AllowEdit || getQueryString().AllowEdit == false || getQueryString().AllowEdit == 'false')) {
            draftEditing = true;
        }
        if ((getQueryString().AllowEdit && (getQueryString().AllowEdit == false || getQueryString().AllowEdit == 'false'))) {
            draftEditing = false;
        }
        else {
            draftEditing = true;
        }


        var active_page = parseInt($(".ap_tp_num_active").text());
        localStorage.setItem('navigatedpages', active_page + ' to ' + newPageNumber);

        if (draftEditing == true) {

            if ($("#save_as_draft_submit_form").length) {
                localStorage.setItem('automatic', 1);
                localStorage.setItem("automaticDraft", 1);
                localStorage.setItem("pagenavigationclicked", 1);

                if (window.location.href.indexOf("/view.php") == -1) {
                    saveAsDraftMessage();
                }


            }

            if ($('#save_as_draft_allow_edit').length) {

                localStorage.setItem("automaticDraft", 1);



            }

        }
        var localstorageData = (localStorage.getItem("pageNavigation")) ? JSON.parse(localStorage.getItem("pageNavigation")) : false;

        var active_page = parseInt($(".ap_tp_num_active").text());
        localStorage.setItem('automatic', 1);
        localStorage.setItem("automaticDraft", 1);
        localStorage.setItem("pagenavigationclicked", 1);
        localStorage.setItem('pageclick', 1);

        localStorage.setItem('navigatedpages', active_page + ' to ' + newPageNumber);



        //save as draft msg

        if (draftFail == 1) {
            return false;
        } else {

            var total_page_count = $(".pagination-links").length;

            var diff = Math.abs(newPageNumber - active_page);
            var next = (newPageNumber > active_page) ? true : false;
            if (newPageNumber == active_page) return false;
            if (localstorageData == false && diff == 1) { //directly clicking to immediate page.
                if (next == true) {
                    $("#submit_primary").trigger("click");
                } else {
                    if ($("input[name=next_page_number]").length) $("input[name=next_page_number]").remove();
                    $("input[name=page_number]").after("<input type='hidden' name='next_page_number'>");
                    $("input[name=next_page_number]").val(newPageNumber);
                    localStorage.removeItem("pageNavigation");
                    $("#submit_secondary").trigger("click");

                }
            } else if (localstorageData == false && diff > 1) { //first time click to far page....
                if (next == true) { //Next action......
                    var pageNumberArray = [];
                    for (i = 1; i < diff + 1; i++) {

                        pageNumberArray.push(active_page + i);
                    }
                    localStorage.setItem("pageNavigation", JSON.stringify(pageNumberArray));
                    localStorage.setItem("formUniqueID", getQueryString().uniqueFormIdentity);

                    $("#submit_primary").trigger("click");
                } else { //Prev action
                    localStorage.removeItem("pageNavigation");
                    if ($("input[name=next_page_number]").length) $("input[name=next_page_number]").remove();
                    $("input[name=page_number]").after("<input type='hidden' name='next_page_number'>");
                    $("input[name=next_page_number]").val(newPageNumber);
                    $("#submit_secondary").trigger("click");
                }

            }
            if ($("#review_back").length > 0) {
                localStorage.removeItem("pageNavigation");
                $("input[name=mf_page_from]").val(newPageNumber);
                $("#review_back").trigger("click");
            }
        }


        //save as draft msg
        localStorage.setItem("pagenavigationclicked", 0);
    }

    /*======================================================PAGE NAVIGATION=================================================================================*/
    var ptid = getQueryString().patientId;
    var fid = getQueryString().id;
    AllowEdit = getQueryString().AllowEdit;
    loggedTenant_id = getQueryString().tenantId;
    if (getQueryString().loginUserId != undefined) {
        loggedUser_id = getQueryString().loginUserId;
        localStorage.setItem('loginUserId', loggedUser_id);
    } else {
        loggedUser_id = localStorage.getItem('loginUserId');
    }

    if (getQueryString().entryId != undefined) {
        entryId = getQueryString().entryId;
        localStorage.setItem('entryId', entryId);
    } else {
        entryId = "";
    }


    const base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
    if (getQueryString().authenticationToken != undefined) {
        loggedAuthKey = getQueryString().authenticationToken;
        
        if(base64regex.test(loggedAuthKey)){
            localStorage.setItem('authkeys', atob(decodeURIComponent(loggedAuthKey)));
            loggedAuthKey = atob(decodeURIComponent(loggedAuthKey));
        }else {
            localStorage.setItem('authkeys', loggedAuthKey);
        }
        
    } else {
        loggedAuthKey = localStorage.getItem('authkeys');
        if(base64regex.test(loggedAuthKey))  loggedAuthKey= atob(decodeURIComponent(loggedAuthKey));
       
    }
    loadformType = getQueryString().formType;

    var recepientsCount = getQueryString().receipientCount;
    if (getQueryString().receipientCount) {
        localStorage.setItem('recepientsCountMsg', getQueryString().receipientCount);

        localStorage.setItem('fromdrafts', 0);


    }
    if (getQueryString().flowcheck) {
        localStorage.setItem('flowcheck', getQueryString().flowcheck);
    }
    if (getQueryString().staffFacing) {

        localStorage.setItem('staffFacingMsg', getQueryString().staffFacing);

    }
    if (ptid) {
        localStorage.setItem('ptid', ptid);
        if (localStorage.getItem('submissionidNewstored')) {
            localStorage.setItem('ptidsubmissionidNewstored', localStorage.getItem('submissionidNewstored'));
        }

    }


    var serverBaseUrlstored = getQueryString().serverBaseUrl;
    baseurlLogged = getQueryString().serverBaseUrl;

    if (baseurlLogged == "undefined" || baseurlLogged == undefined) {
        baseurlLogged = localStorage.getItem('serverBaseUrl');
        baseurlLogged = localStorage.getItem('serverBaseUrlstored');
    }

    var formidstored = getQueryString().id;
    var senderIdstored = getQueryString().toId;
    uniQueFormIdentity = getQueryString().uniqueFormIdentity;
    var tenantIdstored = getQueryString().tenantId;
    var sentIdstored = getQueryString().sentId;
    if (getQueryString().sentId && getQueryString().sentId != null && getQueryString().sentId != 'null' && getQueryString().sentId != 'undefined') {
        localStorage.setItem('sentIdstoredsessionout', sentIdstored);
        $(".manage-role-btn").hide();

    } else {
        localStorage.setItem('sentIdstoredsessionout', "");
    }


    if (getQueryString().savedDraftid) {
        localStorage.setItem('fromdrafts', 1);
        submissionidNew = getQueryString().savedDraftid;
        localStorage.setItem('submissionidNewstored', submissionidNew);
        localStorage.setItem('ptidsubmissionidNewstored', localStorage.getItem('submissionidNewstored'));
    } else {

        if (getQueryString().formCleared) {

        } else {
            if (getQueryString().id)
                localStorage.setItem('submissionidNewstored', 0);
            localStorage.setItem('submissionidNewstoredFill', 0);
        }
    }




    if (getQueryString().clientId) {
        clientId = getQueryString().clientId;
    }
    if (getQueryString().recipientset) {
        practitionerid = getQueryString().recipientset;
        if (practitionerid)
            localStorage.setItem('ptidpractitionerid', practitionerid);
    }
    if (getQueryString().id) {
        formidstored = getQueryString().id;
        localStorage.setItem('formidstored', formidstored);
    }
    if (localStorage.getItem('savedformElementsAuto') === null || localStorage.getItem('savedformElementsAuto') == "") {



        localStorage.setItem('fid', fid);
        localStorage.setItem('savedformElementsAuto', JSON.stringify(formElements));
        localStorage.setItem('ptid', ptid);
        if (localStorage.getItem('submissionidNewstored')) {
            localStorage.setItem('ptidsubmissionidNewstored', localStorage.getItem('submissionidNewstored'));
        }
        localStorage.setItem('serverBaseUrlstored', serverBaseUrlstored);
        localStorage.setItem('formidstored', formidstored);
        localStorage.setItem('senderIdstored', senderIdstored);
        localStorage.setItem('tenantIdstored', tenantIdstored);
        localStorage.setItem('sentIdstored', sentIdstored);



    }

    if ((ptid && localStorage.getItem('ptid') != ptid) || localStorage.getItem('ptid') == "" || localStorage.getItem('ptid') == null || localStorage.getItem('ptid') == "undefined" || localStorage.getItem('ptid') == undefined) {

        localStorage.setItem('savedformElementsAuto', JSON.stringify(formElements));


    }
    if (localStorage.getItem('fid') != fid || localStorage.getItem('fid') == "" || localStorage.getItem('fid') == null || localStorage.getItem('fid') == "undefined" || localStorage.getItem('fid') == undefined) {

        localStorage.setItem('savedformElementsAuto', JSON.stringify(formElements));
        localStorage.setItem('fid', fid);


    }
    var serverBaseUrl = getQueryString().serverBaseUrl;
    if (serverBaseUrl == "undefined" || serverBaseUrl == undefined) {
        serverBaseUrl = localStorage.getItem('serverBaseUrl');
        serverBaseUrl = localStorage.getItem('serverBaseUrlstored');
    }
    var formid = getQueryString().id;
    var senderId = getQueryString().toId;
    var tenantId = getQueryString().tenantId;
    var sentId = getQueryString().sentId;
    if (!senderId) {
        senderId = localStorage.getItem('senderIdstored');
    }
    if (!tenantId) {
        tenantId = localStorage.getItem('tenantIdstored');
    }
    if (!sentId) {
        sentId = localStorage.getItem('sentIdstored');
    }
    if (!formid || formid == "undefined" || formid == undefined) {
        formid = localStorage.getItem('formid');
    }
    if (!formid || formid == "undefined" || formid == undefined) {
        formid = localStorage.getItem('formidstoredn');
    }
    if (!formid) {
        formid = localStorage.getItem('formidstored');
    }

    if (getQueryString().tenantId && getQueryString().serverBaseUrl) {

        localStorage.setItem('normalFlow', getQueryString().id);
    } else {

        if (!localStorage.getItem('serverBaseUrlstored') || localStorage.getItem('normalFlow') != getQueryString().id)
            if (getQueryString().id && localStorage.getItem('confirm_back') != 1) {

                $("#save_as_draft_submit_form").hide();
            }

    }
    $("input").blur(function () {
        var typeautosavetype = $(this).attr("type");
        var typeautosaveId = $(this).attr("id");

        $(this).toggleClass("focused");
        if (!$('.mf_sig_wrapper').length) {


            if ((getQueryString().tenantId && getQueryString().serverBaseUrl && getQueryString().patientId) || (localStorage.getItem('normalFlow') == getQueryString().id && getQueryString().patientId)) {
                if (typeautosavetype == "text") {
                    if (getQueryString().staffFacing != "true") {

                        $("#" + typeautosaveId).trigger("click");
                    }

                }

            }
        }


    });

    var authToken = decodeURIComponent(getQueryString().authenticationToken);
    var clickeditem = "input,select,textarea";
    var embed = (getQueryString().formType && getQueryString().formType != 'undefined' && getQueryString().formType == 'worklist') ? true : false;
    var embedallowedit = (getQueryString().AllowEdit && getQueryString().AllowEdit != 'undefined' && (getQueryString().AllowEdit == 'true' || getQueryString().AllowEdit == true)) ? true : false;
    var embedstaff = (getQueryString().staffFacing && getQueryString().staffFacing != 'undefined' && (getQueryString().staffFacing == 'true' || getQueryString().staffFacing == true)) ? true : false;
    if (embed == true) {

    }
    else if (embedallowedit == true && embedstaff == true) {
        embed = false;
    }
    else if (embedallowedit == false && embedstaff == true) {
        embed = true;
    }

    if (embed != true && ((tenantId && serverBaseUrl && getQueryString().patientId) || localStorage.getItem('normalFlow') == formid) && senderId) {
        clickeditem = "input,select,textarea";
    }
    else {


        var total_page_count_check = $(".pagination-links").length;

        if (total_page_count_check == 0) {

            clickeditem = "#save_as_draft_submit_form";
        }
    }

    $("input,select,textarea").click(function () {

        if (saveDraftValue == false && counter == '') intimate_user_to_save(false, false);
        saveDraftValue = false;

    });



    function getQueryStringOld() {


        var queryStringKeyValue = window.location.search.replace('?', '').split('&');
        if (window.location.search && (window.location.search.includes("?id=") == true || window.location.search.includes("?id=") == "true")) {

        } else {
            localStorage.setItem('confirm_back', 1);
        }

        var qsJsonObject = {};
        if (queryStringKeyValue != '') {
            for (i = 0; i < queryStringKeyValue.length; i++) {
                qsJsonObject[queryStringKeyValue[i].split('=')[0]] = queryStringKeyValue[i].split('=')[1];
            }
        } else {
            qsJsonObject = "";
        }

        return qsJsonObject;
    }
    function getQueryStringCheck() {


        if (documentreferrer && (documentreferrer.includes(".com") == true || documentreferrer.includes(".com") == "true" || documentreferrer.includes(":") == true)) {
            if (documentreferrer.includes("embed.php") != true) {


                localStorage.setItem('ptidsubmissionidNewstored', 0);
                localStorage.setItem('ptidpractitionerid', 0);

                localStorage.setItem('submissionidNewstored', 0)
                localStorage.setItem('confirm_back', 0);
                localStorage.setItem('documentreferrerstored', '');
                localStorage.setItem('enableCollaborateEdit', 0);
                localStorage.setItem('saveasdraftidtodeleted', 0);
                localStorage.setItem('populatePreviousSubmission', 0);
                localStorage.setItem('draftsavedataFinal', 0);
                setCookie('normalFlow', 0, 1);

                setCookie('saveasdraftidtodeleted', 0, 1);
            }


        }
        if (documentreferrer == "") {
            localStorage.setItem('ptidsubmissionidNewstored', 0);
            localStorage.setItem('ptidpractitionerid', 0);
            localStorage.setItem('submissionidNewstored', 0)
            localStorage.setItem('confirm_back', 0);
            localStorage.setItem('documentreferrerstored', '');
            localStorage.setItem('enableCollaborateEdit', 0);
            localStorage.setItem('saveasdraftidtodeleted', 0);
            localStorage.setItem('populatePreviousSubmission', 0);
            localStorage.setItem('draftsavedataFinal', 0);
            setCookie('normalFlow', 0, 1);

            setCookie('saveasdraftidtodeleted', 0, 1);
        }

        var queryStringKeyValue = window.location.search.replace('?', '').split('&');

        var qsJsonObject = {};
        if (queryStringKeyValue != '') {
            for (i = 0; i < queryStringKeyValue.length; i++) {
                qsJsonObject[queryStringKeyValue[i].split('=')[0]] = queryStringKeyValue[i].split('=')[1];
            }
        } else {
            qsJsonObject = "";
        }

        return qsJsonObject;
    }





    function getQueryString() {


        if (documentreferrer && (documentreferrer.includes("/embed.php?id=") == true || documentreferrer.includes("/embed.php?id=") == "true")) {

            var queryStringKeyValue = documentreferrer.replace('?', '').split('&');
            localStorage.setItem('documentreferrerstored', documentreferrer);

        } else if (documentreferrer && (documentreferrer.includes("/embed.php") == true || documentreferrer.includes("/embed.php") == "true")) {


            var queryStringKeyValue = localStorage.getItem('documentreferrerstored').replace('?', '').split('&');
            localStorage.setItem('confirm_back', 1);
        } else if (window.location.search.includes("embed.php?back=true") == true || window.location.search.includes("embed.php?back=true") == "true") {

            var queryStringKeyValue = localStorage.getItem('documentreferrerstored').replace('?', '').split('&');
            localStorage.setItem('confirm_back', 1);
        } else if (window.location.search.includes("_embed.php") == true || window.location.search.includes("_embed.php") == "true") {

            var queryStringKeyValue = localStorage.getItem('documentreferrerstored').replace('?', '&').split('&');

        }
        else {


            var queryStringKeyValue = window.location.search.replace('?', '').split('&');


        }

        if (window.location.search.includes("?id=") == true || window.location.search.includes("?id=") == "true") {
            var queryStringKeyValue = window.location.search.replace('?', '').split('&');
        }
        var qsJsonObject = {};
        if (queryStringKeyValue != '') {
            for (i = 0; i < queryStringKeyValue.length; i++) {
                var queryVal= queryStringKeyValue[i].slice(queryStringKeyValue[i].indexOf('=') + 1);
                var queryKey= queryStringKeyValue[i].slice(0, queryStringKeyValue[i].indexOf('='));
                if(queryKey && queryKey=='authenticationToken'){
                    if($("#headerAuthToken").length && $("#headerAuthToken").val()!='') queryVal= $("#headerAuthToken").val();
                    if(queryStringKeyValue.join().includes('formVersion=')){
                        qsJsonObject[queryKey] = atob(decodeURIComponent(queryVal));
                    }else{
                        qsJsonObject[queryKey] = queryVal;
                    }
                    
                }else {
                    qsJsonObject[queryKey] = queryVal;
                }
                
                
            }
            if("authenticationToken" in qsJsonObject!==true && $("#headerAuthToken").length && $("#headerAuthToken").val()!=''){
                qsJsonObject["authenticationToken"] = $("#headerAuthToken").val();
            }
        } else {
            qsJsonObject = "";
        }

        return qsJsonObject;
    }
    var storageData = getQueryString();

    var autoSave = (storageData && storageData.autoSave) ? storageData.autoSave : "undefined";

    var savaAsDraftStaff = getQueryString().savaAsDraftStaff;

    if (savaAsDraftStaff) {
        localStorage.setItem('savaAsDraftStaff', savaAsDraftStaff);
    }

    var savaAsDraftPatient = getQueryString().savaAsDraftPatient;
    var savaAsDraftstafffacing = getQueryString().staffFacing;
    var savaAsDraftstafffilling = getQueryString().staffFilling;
    var staffSubmissionId = getQueryString().staffSubmissionId;
    var recipientEmail = getQueryString().recipientEmail;
    if (savaAsDraftPatient == "undefined" || savaAsDraftPatient == undefined) {

        if (localStorage.getItem('savaAsDraftstafffacing') == "staffsupplyCount" || getQueryString().staffFacing == "staffsupplyCount") {

            $("#save_as_draft_submit_form").hide();
        }
    }
    if (autoSave == "undefined" || autoSave == undefined) {

        autoSave = localStorage.getItem('autoSave');

    }
    if (savaAsDraftStaff == "undefined" || savaAsDraftStaff == undefined) {
        savaAsDraftStaff = localStorage.getItem('savaAsDraftStaff');
    }
    if (savaAsDraftPatient == "undefined" || savaAsDraftPatient == undefined) {
        savaAsDraftPatient = localStorage.getItem('savaAsDraftPatient');
    }
    if (savaAsDraftstafffacing == "undefined" || savaAsDraftstafffacing == undefined) {
        savaAsDraftstafffacing = localStorage.getItem('savaAsDraftstafffacing');
    }
    if (savaAsDraftstafffilling == "undefined" || savaAsDraftstafffilling == undefined) {
        savaAsDraftstafffilling = localStorage.getItem('savaAsDraftstafffilling');
    }
    if (staffSubmissionId == "undefined" || staffSubmissionId == undefined) {
        staffSubmissionId = localStorage.getItem('staffSubmissionId');
    }
    if (recipientEmail == "undefined" || recipientEmail == undefined) {
        recipientEmail = localStorage.getItem('recipientEmail');
    }
    var sentidpatient = getQueryString().sentId;
    var formTypeWorkList = (typeof getQueryString().formType!=='undefined' && getQueryString().formType && getQueryString().formType != 'undefined' && getQueryString().formType == 'worklist') ? true : false;
    var formTypeConsolo=(typeof getQueryString().consoloSubmission!=='undefined' && getQueryString().consoloSubmission && getQueryString().consoloSubmission != 'undefined' && getQueryString().consoloSubmission ==1)?true:false;
    if (savaAsDraftPatient != 1 && sentidpatient && localStorage.getItem('confirm_back') != 1) {
        if (sentidpatient != "null" && sentidpatient != null && sentidpatient != undefined && sentidpatient != "undefined" && sentidpatient != "") {

            $("#save_as_draft_submit_form").hide();
        } else {

            if(formTypeWorkList!=true && formTypeConsolo!=true) $("#save_as_draft_submit_form").show();
        }

    }

    if ((savaAsDraftstafffacing == true || savaAsDraftstafffacing == "true") && savaAsDraftStaff != 1 && localStorage.getItem('confirm_back') != 1) {

        $("#save_as_draft_submit_form").hide();
    }
    if ((savaAsDraftstafffilling == true || savaAsDraftstafffilling == "true") && savaAsDraftStaff != 1 && localStorage.getItem('confirm_back') != 1) {

        $("#save_as_draft_submit_form").hide();
    }
    if (savaAsDraftStaff != 1 && localStorage.getItem('confirm_back') != 1) {


        $("#save_as_draft_submit_form").hide();



    }
    if(typeof getQueryString==="function" && typeof getQueryString().saveAsDraftPatient!=='undefined' && getQueryString().saveAsDraftPatient==1){
        $("#save_as_draft_submit_form").show();
    }

    if (localStorage.getItem('staffFacingMsg') == 1 && formTypeWorkList!=true && formTypeConsolo!=true) {
        $("#save_as_draft_submit_form").show();
    }
    var formid = getQueryString().id;
    var recepientId = getQueryString().patientId;
    var senderId = getQueryString().toId;
    var tenantId = getQueryString().tenantId;
    var sentId = getQueryString().sentId;
    var serverBaseUrl = getQueryString().serverBaseUrl;
    var recepientsCount = getQueryString().receipientCount;

    if (formid == "undefined" || formid == undefined) {
        formid = localStorage.getItem('formid');

    }
    if (recepientId == "undefined" || recepientId == undefined) {

        recepientId = localStorage.getItem('ptid');
    }
    if (senderId == "undefined" || senderId == undefined) {
        senderId = localStorage.getItem('senderId');
        senderId = localStorage.getItem('senderIdstored');
    }
    if (tenantId == "undefined" || tenantId == undefined) {
        tenantId = localStorage.getItem('tenantId');
        tenantId = localStorage.getItem('tenantIdstored');
    }
    if (sentId == "undefined" || sentId == undefined) {
        sentId = localStorage.getItem('sentId');
        sentId = localStorage.getItem('sentIdstored');
    }
    if (serverBaseUrl == "undefined" || serverBaseUrl == undefined) {
        serverBaseUrl = localStorage.getItem('serverBaseUrl');
        serverBaseUrl = localStorage.getItem('serverBaseUrlstored');
    }
    if (recepientsCount == "undefined" || recepientsCount == undefined) {
        recepientsCount = localStorage.getItem('receipientCount');
    }

    if (!senderId) {
        senderId = localStorage.getItem('senderIdstored');
    }
    if (!tenantId) {
        tenantId = localStorage.getItem('tenantIdstored');
    }
    if (!sentId) {
        sentId = localStorage.getItem('sentIdstored');
    }
    if (!formid || formid == "undefined" || formid == undefined) {
        formid = localStorage.getItem('formid');
    }
    if (!formid || formid == "undefined" || formid == undefined) {
        formid = localStorage.getItem('formidstoredn');
    }
    if (!formid) {
        formid = localStorage.getItem('formidstored');
    }
    var stafffacing = true;
    if (sentidpatient != "null" && sentidpatient != null && sentidpatient != undefined && sentidpatient != "undefined" && sentidpatient != "") {
        stafffacing = false;
    } else {
        stafffacing = true;
    }

    if (recepientId != "undefined" && recepientId != undefined) {
        recepientId = recepientId;

    } else {

        recepientId = getQueryString().loginUserId;

        if (recepientId == "undefined" || recepientId == undefined) {
            recepientId = localStorage.getItem('loginUserId');
        }
        stafffacing = false;


    }
    if (recepientId != "undefined" && recepientId != undefined) {
        if (recepientId.includes("--")) {
            var myarray = recepientId.split('--');
            recepientId = myarray[1];
        }
    }
    if (sentId && (!recepientId || recepientId == 0)) {
        recepientId = getQueryString().loginUserId;
    }

    if (recepientId == undefined || recepientId == "undefined") {
        recepientId = localStorage.getItem('ptid');
    }

    function timeConvertor(time) {
        var PM = time.match('PM') ? true : false

        time = time.split(':')
        var min = time[1]

        if (PM) {
            var hour = 12 + parseInt(time[0], 10)
            var sec = time[2].replace('PM', '')
        } else {
            var hour = time[0]
            var sec = time[2].replace('AM', '')
        }

        return (hour + ':' + min + ':' + sec)
    }

    function findWithAttr(array, attr, value) {
        for (var i = 0; i < array.length; i += 1) {
            if (array[i][attr] === value) {
                return i;
            }
        }
        return -1;
    }
    var idsofOther = '';
    var inp = "input";
    var form = "form#form_" + formid;




    //save as draft API call 
    var authToken = decodeURIComponent(getQueryString().authenticationToken);

    $('#save_as_draft_submit_form').click(function (event, pageclick, btnidentity, navigatingpagno) {

        if (pageclick == 1) {
            localStorage.setItem('pageclick', 1)
        } else {
            localStorage.setItem('pageclick', 0)
        }

        saveDraftValue = true;
        counter ? intimate_user_to_save(false, true) : null;

        $('#save_as_draft_submit_form').prop('disabled', true);
        if (!localStorage.getItem('automaticDraft') || localStorage.getItem('automaticDraft') == null) {
            localStorage.setItem('automatic', null)
            $.postMessage({ saveAsDraftCall: true }, '*');
            $("#save_as_draft_submit_form").val('Saving');

        }
        matrix = [];

        $(".select ").each(function () {
            var val = $(this).val();
            var id = $(this).attr("id");
            var find = findWithAttr(formElements, 'id', id);
            if (val != "AM" && val != "PM") {
                if (find == -1) {
                    formElements.push({ "id": id, "value": val, "type": "select" });
                } else {
                    formElements[find]['value'] = val;

                }
            }

        });
        $(".multiple_choice input:not([type=hidden])").each(function () {
            var id = $(this).attr("name");
            var idss = $(this).attr("id");
            var val = $(this).val();

            if ($(this).is(":checked")) {
                val = $(this).val();
            } else { val = ""; }
            var find = findWithAttr(formElements, 'id', id);
            if (idss.includes("_0")) {
                if (!idsofOther.includes(idss)) {
                    if (idsofOther == "") {
                        idsofOther = idss;
                        formElements.push({ "id": id, "value": val, "type": "radio" });

                    } else
                        idsofOther = idsofOther + ',' + idss;

                }
            }
            if (id.includes("_")) {
                if (find == -1) {
                    if (val)
                        formElements.push({ "id": id, "value": val, "type": "radio" });

                } else {
                    formElements[find]['value'] = val;



                }



            }

        });
        var checkingflag = 1;
            $(".multiple_choice input:not([type=hidden])").each(function () {

                var id = $(this).attr("name");
                var val = $(this).val();

                if ($(this).is(":checked")) {

                    checkingflag = 0
                    val = $(this).val();
                    formElements.push({ "id": id, "value": val, "type": "radio" });
                } else {
                    if (checkingflag == 1) {
                        val = "";
                        formElements.push({ "id": id, "value": val, "type": "radio" });
                    }

                }


            });

        $(".matrix input[type=checkbox]").each(function () {
            var id = $(this).attr("name");
            var val;
            var find = findWithAttr(formElements, 'id', id);

            if ($(this).prop("checked") == true) {

                var y = id.split("_");
                val = y[y.length - 1];

            }
            else if ($(this).prop("checked") == false) {
                val = 0;
            }
            if (find == -1) {
                formElements.push({ "id": id, "value": val, "type": "checkbox" });

            } else {
                for (var i = 0; i < formElements.length; i += 1) {
                    if (formElements[i]['id'] === id) {


                        formElements[i]['value'] = val;
                    }
                }



            }


        })


        $(".matrix input[type='radio']:checked").each(function () {

            var id = $(this).attr("name");

            var val = $(this).val();

            matrix.push({ "id": id, "value": val, "type": "radio" });



        })



        var ids = [];
        var clean = [];

        $.each(matrix, function (index, value) {
            if ($.inArray(value.id, ids) == -1) {
                ids.push(value.id);
                clean.push(value);
            } else {
                clean[$.inArray(value.id, ids)]['value'] = value.value;
            }
        });



        formElements = formElements.concat(clean);
        $(".checkboxes input:not([type=hidden])").each(function () {
            var val;
            if ($(this).attr("checked") == "checked") {

                if (val == 0) {
                    val = 1;
                }
                val = 0;
            } else {

                if (val == 1) {
                    val = 0;
                }
                val = 1;
            }
            if ($(this).prop("checked") == true) {
                val = 1;
            }
            else if ($(this).prop("checked") == false) {
                val = 0;
            }
            var id = $(this).attr("id");
            var find = findWithAttr(formElements, 'id', id);


            //var val = $(this).val();
            if (id.includes("_0")) {
                if (!idsofOther.includes(id)) {
                    if (idsofOther == "")
                        idsofOther = id;
                    else
                        idsofOther = idsofOther + ',' + id;
                }

            } else {
                if (find == -1) {
                    if (val == 1 || val == 0)

                        formElements.push({ "id": id, "value": val, "type": "checkbox" });
                } else {

                    formElements.push({ "id": id, "value": val, "type": "checkbox" });
                }

            }


        })

        if (idsofOther != "") {
            var arrayofother = idsofOther.split(",");
            arrayofother.forEach(function (item) {
                var res = item.replace("_0", "_other");
                var otherval = $("#" + res).val();
                formElements.push({ "id": res, "value": otherval, "type": "textother" });
            });
        }
        localStorage.setItem('savedformElementsAuto', JSON.stringify([]));

        sessionStorage.setItem("saveAsDraft", "true");
        document.cookie = "saveAsDraft = " + "true";

        $('textarea').each(
            function () {
                formElements.push({ "id": $(this).attr('id'), "value": $(this).val(), "type": "textarea" });

            }
        );

        $('form.appnitro input').each(function () {
            var input = $(this); // This is the jquery object of the input, do what you will

            if ($(this).attr('id') != undefined && $(this).attr("type") != "checkbox" && $(this).attr("type") != "radio" && $(this).attr("type") != "hidden" && $(this).attr("type") != "submit" && $(this).attr("type") != "button" && $(this).attr("type") != "file" && $(this).attr("type") != "image") {

                var str = $(this).attr('id')
                if (str.includes("_0") || str.includes("_other")) {

                    if (str.includes("_0")) {
                        var res = item.replace("_0", "");
                        var find = findWithAttr(formElements, 'id', res);
                        if (find == -1) {

                            formElements.push({ "id": res, "value": 0, "type": "othertext" });
                        }
                    }
                    var find = findWithAttr(formElements, 'id', str);
                    var otherval = $("#" + str).val();
                    if (find == -1) {

                        formElements.push({ "id": str, "value": otherval, "type": "othertext" });
                    }

                } else {
                    if ($(this).parent().parent().parent().hasClass("date_field")) {
                        var iddate = $(this).parent().parent().parent().attr("id");
                        var iddatenn = iddate.replace("li", "");
                        var idsss = "element" + iddatenn;
                        var valuedate = $("#" + idsss + "_datepick").val();
                        var str = valuedate;
                        var myarray = str.split('/');
                        myarray[2] = $("#" + idsss + "_3").val();
                        myarray[1] = $("#" + idsss + "_2").val();
                        myarray[0] = $("#" + idsss + "_1").val();
                        valuedate = myarray[2] + "-" + myarray[0] + "-" + myarray[1];
                        var find = findWithAttr(formElements, 'id', idsss);
                        if (myarray[2] && myarray[0] && myarray[1]) { } else {
                            valuedate = "";
                        }

                        if (myarray[2] && myarray[0] && myarray[1]) {
                            formElements.push({ "id": idsss, "value": valuedate, "type": "date" });
                        } else {
                            valuedate = "";
                            formElements.push({ "id": idsss, "value": valuedate, "type": "date" });
                        }



                    } else {
                        if ($(this).parent().parent().parent().hasClass("phone")) {
                            var iddate = $(this).parent().parent().parent().attr("id");
                            var iddatenn = iddate.replace("li", "");
                            var idsss = "element" + iddatenn;
                            var first = $("#" + idsss + "_1").val();
                            var second = $("#" + idsss + "_2").val();
                            var third = $("#" + idsss + "_3").val();

                            var timeupdated = "";
                            var find = findWithAttr(formElements, 'id', idsss);
                            if (first && second && third) {
                                timeupdated = first + second + third;
                            } else {
                                timeupdated = "";
                            }
                            if (find == -1) {

                                formElements.push({ "id": idsss, "value": timeupdated, "type": "phonr" });
                            } else {
                                formElements[find]['value'] = timeupdated;
                            }
                        }
                        else if ($(this).parent().parent().parent().hasClass("europe_date_field")) {
                            var iddate = $(this).parent().parent().parent().attr("id");
                            var iddatenn = iddate.replace("li", "");
                            var idsss = "element" + iddatenn;
                            var valuedate = $("#" + idsss + "_datepick").val();
                            var str = valuedate;
                            var myarray = str.split('/');
                            myarray[2] = $("#" + idsss + "_3").val();
                            myarray[1] = $("#" + idsss + "_2").val();
                            myarray[0] = $("#" + idsss + "_1").val();
                            valuedate = myarray[2] + "-" + myarray[1] + "-" + myarray[0];
                            var find = findWithAttr(formElements, 'id', idsss);
                            if (myarray[2] && myarray[0] && myarray[1]) { } else {
                                valuedate = "";
                            }

                            if (myarray[2] && myarray[0] && myarray[1]) {
                                formElements.push({ "id": idsss, "value": valuedate, "type": "date" });
                            } else {
                                valuedate = "";
                                formElements.push({ "id": idsss, "value": valuedate, "type": "date" });
                            }



                        }
                        else if ($(this).parent().parent().parent().hasClass("time_field")) {

                            var iddate = $(this).parent().parent().parent().attr("id");
                            var iddatenn = iddate.replace("li", "");
                            var idsss = "element" + iddatenn;
                            var hour = $("#" + idsss + "_1").val();
                            var min = $("#" + idsss + "_2").val();

                            var am = $("#" + idsss + "_4").val();
                            var timeupdated = timeConvertor('"' + hour + ':' + min + ':00' + am + '"');
                            timeupdated = hour + ':' + min + ':00';
                            if (am == "PM" && parseInt(hour) < 12) {
                                hour = parseInt(hour) + parseInt(12);
                                timeupdated = hour + ':' + min + ':00';
                            } else if (am == "PM" && parseInt(hour) == 12) {
                                timeupdated = hour + ':' + min + ':00';
                            } else if (am == "AM" && parseInt(hour) == 12) {
                                hour = parseInt(hour) - 12;
                                hour=hour.toString();
                                timeupdated = hour + ':' + min + ':00';
                            }
                            else {
                                timeupdated = hour + ':' + min + ':00';
                            }
                            var find = findWithAttr(formElements, 'id', idsss);
                            if (hour && min) {
                                timeupdated = timeupdated;
                            } else {
                                timeupdated = null;
                            }
                            if (find == -1) {
                                if (hour && min) {
                                    timeupdated = timeupdated;
                                } else {
                                    timeupdated = null;
                                }
                                formElements.push({ "id": idsss, "value": timeupdated, "type": "time" });
                            } else {
                                formElements[find]['value'] = timeupdated;
                            }
                        } else if ($(this).parent().parent().hasClass("price")) {
                            var idss = $(this).attr('id');
                            var splitname = idss.substr(idss.length - 2);
                            if (splitname == "_1") {


                                var idssreplaced = idss.replace(new RegExp('_1' + '$'), '');
                                var valdoller = $("#" + idssreplaced + "_1").val();

                                var valcent = $("#" + idssreplaced + "_2").val();

                                var valupdated = valdoller + "." + valcent;

                                if (valdoller!='' || valcent!='') {

                                    if (valdoller != undefined && valcent != undefined) {

                                        if(valdoller && valcent) var valupdated = valdoller + "." + valcent;
                                        else if(valdoller && valcent=='') var valupdated = valdoller+'.0';
                                        else var valupdated = '0.'+valcent;
                                        

                                        formElements.push({ "id": idssreplaced, "value": valupdated, "type": "price" });

                                    }
                                }

                            }


                        } else {
                            var find = findWithAttr(formElements, 'id', $(this).attr('id'));
                            if (find == -1) {
                                formElements.push({ "id": $(this).attr('id'), "value": $(this).val(), "type": $(this).attr("type") });
                            } else {
                                formElements[find]['value'] = $(this).val();
                            }
                        }


                    }

                }


            }
        });

        $(".mf_sig_wrapper input").each(function () {
            var val = $(this).val();
            var id = $(this).attr("id");
            var find = findWithAttr(formElements, 'id', id);
            if (find == -1) {
                formElements.push({ "id": id, "value": val, "type": "signature" });
            } else {
                formElements[find]['value'] = val;
            }
        });
        formElements = formElements.concat(matrix);

        var cleanformElements = [];
        var idsformElements = [];
        $.each(formElements, function (index, value) {
        if(typeof value!=='undefined' && value!==null && typeof value.id!=='undefined' && value.id!==null &&  value.id.includes('_confirm')==false){
            if ($.inArray(value.id, idsformElements) == -1) {
                idsformElements.push(value.id);
                cleanformElements.push(value);
            } else {
                cleanformElements[$.inArray(value.id, idsformElements)]['value'] = value.value;
            }
        }

        });

        serverBaseUrl = getQueryString().serverBaseUrl;

        if (!serverBaseUrl || serverBaseUrl == "undefined" || serverBaseUrl == undefined) {
            serverBaseUrl = localStorage.getItem('serverBaseUrlstored');


        } else if (serverBaseUrl.indexOf("machform/Upload")) {
            if (localStorage.getItem('serverBaseUrlstoredn') || localStorage.getItem('serverBaseUrlstoredn') == "undefined" || localStorage.getItem('serverBaseUrlstoredn') == undefined) {
                if (!serverBaseUrl) {
                    serverBaseUrl = localStorage.getItem('serverBaseUrlstoredn');

                }

            }

        }
        if (!formid || formid == "undefined" || formid == undefined) {
            formid = localStorage.getItem('formid');
        }
        if (!formid || formid == "undefined" || formid == undefined) {
            formid = localStorage.getItem('formidstoredn');
        }
        if (!tenantId || tenantId == "undefined" || tenantId == undefined) {
            tenantId = localStorage.getItem('tenantIdstoredn');
        }
        if (!senderId || senderId == "undefined" || senderId == undefined) {
            senderId = localStorage.getItem('senderIdstoredn');
        }
        if (!sentId || sentId == "undefined" || sentId == undefined) {
            sentId = localStorage.getItem('sentIdstoredn');
        }



        if (getQueryString().id) {
            formid = getQueryString().id;
        }
        var form = new FormData();

        form.append("formId", formid);
        form.append("tenant_id", tenantId);
        form.append("sender_id", senderId);
        form.append("recepient_id", recepientId);
        form.append("stafffacing", stafffacing);
        form.append("clientId", clientId);
        form.append("sentId", sentId);
        localStorage.setItem('normalFlow', formid);
        if (sentId && sentId != null && sentId != "null" && submissionidNew == 0) {
            if (sentId && sentId != null && sentId != "null" && submissionidNew == 0 && getQueryString().staffSubmissionId && getQueryString().staffSubmissionId != null && getQueryString().staffSubmissionId != "null" && getQueryString().staffSubmissionId != 0) {
            }
            else {
                form.append("submissionId", 0);
            }

        } else {

            if (localStorage.getItem('submissionidNewstored') == 0) {
                if (localStorage.getItem('ptidsubmissionidNewstored') != 0) {
                    form.append("submissionId", localStorage.getItem('ptidsubmissionidNewstored'));
                }

            } else {
                form.append("submissionId", localStorage.getItem('submissionidNewstored'));
            }

        }

        var total_page_count_check = $(".pagination-links").length;

        if (total_page_count_check == 0) {

            if (sentId && sentId != null && sentId != "null" && submissionidNew == 0 && getQueryString().staffSubmissionId && getQueryString().staffSubmissionId != null && getQueryString().staffSubmissionId != "null" && getQueryString().staffSubmissionId != 0) {
                submissionidNew = getQueryString().staffSubmissionId;
                form.append("submissionId", submissionidNew);
            }
        }
        form.append("confirmback", localStorage.getItem('confirm_back'));
        if (localStorage.getItem('ptidpractitionerid') != 0) {
            form.append("practitionerid", localStorage.getItem('ptidpractitionerid'));
        } else {
            form.append("practitionerid", practitionerid);
        }
        var autosvetrack=0;
        if ($(".appnitro").attr("automaticdraftsave") == 1){ form.append("automaticdraftsave", 1); autosvetrack=1;}
        form.append("enableCollaborateEdit", localStorage.getItem('enableCollaborateEdit'));
        if ($(".submit_img_primary").length || $(".submit_img_secondary").length) {
            //form.append("formData", []);
            form.append("formData", JSON.stringify(cleanformElements));
        } else {


            form.append("formData", JSON.stringify(cleanformElements));


        }



        if ($(".confirmed_elements").length) {
            var x = [];
            $(".confirmed_elements").each(function () {
                x.push($(this).val());
            });
            form.append('confirmed_elements', x);
        }
        if ($(".not_confirmed_class").length) {
            var y = [];
            $(".not_confirmed_class").each(function () {
                y.push($(this).val());
            });
            form.append("not_confirmed_elements", y);
        }


        if (localStorage.getItem("numberfields") && localStorage.getItem("numberfields") !== null && localStorage.getItem("numberfields").length) {
            form.append("number_fields", localStorage.getItem("numberfields"));
        }

        if (localStorage.getItem("numberfieldsMoney") && localStorage.getItem("numberfieldsMoney") !== null && localStorage.getItem("numberfieldsMoney").length) {
            form.append("number_fields_money", localStorage.getItem("numberfieldsMoney"));

        }

        if ($(".singlefile:visible").length) {

            var files = [];
            $(".singlefile:visible").each(function () {
                var element_id = $(this).attr("id");
                if (document.getElementById(element_id).files.length) {
                    files.push(element_id);
                    form.append("file[]", $('#' + element_id).prop('files')[0]);
                }
            });

            form.append('filIds', files);
        }

        if ($(".valueChangedElement").length) {
            var x = [];
            $(".valueChangedElement").each(function () {
                var element_id = $(this).attr("id").split("_");
                if (element_id.length && element_id[1]) x.push(element_id[1]);
            });
            form.append("changed_elements", x);
        }

        var serverBaseUrlN = serverBaseUrl.replace("%3A%2F%2F", "://");
        var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
        var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
        var serverBaseUrlN = serverBaseUrlN.replace("machform/Upload/undefined/", "");
        var total_page_count_check = $(".pagination-links").length;
        if (total_page_count_check > 0) {
            if (btnidentity == 'primary') {

                var active_page = parseInt($(".ap_tp_num_active").text());
                var total_page_count_check = $(".pagination-links").length;
                if (active_page == total_page_count_check) {
                    var newPageNumber = active_page;
                } else {
                    var newPageNumber = active_page + 1;
                }
                localStorage.setItem('navigatedpages', active_page + ' to ' + newPageNumber);
            } else if (btnidentity == 'secondary') {

            } else if (btnidentity == 'navigation') {
                var active_page = parseInt($(".ap_tp_num_active").text());
                localStorage.setItem('navigatedpages', active_page + ' to ' + navigatingpagno);
            }

            if (localStorage.getItem('navigatedpages')) {
                form.append("pagesnavigated", localStorage.getItem('navigatedpages'));
            }
        }
        else {
            if (localStorage.getItem('navigatedpages')) {
                form.append("pagesnavigated", 0);
            }
        }

        if (getQueryString().uniqueFormIdentity) {
            form.append("uniqueFormIdentity", getQueryString().uniqueFormIdentity);
        }
        if (getQueryString().draftSave && getQueryString().draftSave == 'true') {
            form.append("draftSave", true);
        }
        if (localStorage.getItem('automatic') && localStorage.getItem('automatic') == 1) {
            localStorage.removeItem('automatic');
            form.append("automatic", true);
        }




        var formSendMode = getQueryString().formSendMode;
        var applessshowerror = 0;
        if (localStorage.getItem("formMode_"+uniQueFormIdentity) != null && localStorage.getItem("formMode_"+uniQueFormIdentity) != "null") {
            let formModeValue = localStorage.getItem("formMode_"+uniQueFormIdentity);
            if(formModeValue == 'appless'){
                form.append('applessMode', 1);
            }else{
                form.append('applessMode', 0);
            }
        }else{
            if (typeof (formSendMode) == 'undefined' || formSendMode != 'appless') {
                form.append('applessMode', 0);
            } else if (formSendMode == 'appless') {
                form.append('applessMode', 1);
                applessshowerror = 1;
            } else {
                form.append('applessMode', 0);
            }
        }
        var tracksubauto=0;
        if (localStorage.getItem('automaticDraft') && localStorage.getItem('automaticDraft') !== null && typeof localStorage.getItem('automaticDraft') !== 'undefined' && localStorage.getItem('automaticDraft') == 1) {
            form.append('automaticDraft', 1);
            tracksubauto=1;
        }
        if (getQueryString().uniqueFormIdentity) {
            form.append("uniqueFormIdentity", getQueryString().uniqueFormIdentity);
        }

        // session unique in multiple tabs checking
        if (getQueryString()) {
            let appendUrl = appendBaseUrl(serverBaseUrl);
            serverBaseUrlN = appendUrl;
            var jsonarray = JSON.stringify(getQueryString());
            var jsonscript = JSON.parse(jsonarray);
            jsonscript['serverBaseUrl'] = appendUrl;
            form.append("request_params", JSON.stringify(jsonscript));
        }
        var authToken = decodeURIComponent(getQueryString().authenticationToken);
        // session unique in multiple tabs checking
        $(".appnitro input").each(function(){
            if($(this).attr('type')=='radio' && $(this).is(':checked')){
                $(this).attr('checked','checked');
            }else if($(this).attr('type')=='checkbox' && $(this).is(':checked')){
                $(this).attr('checked','checked');
            }else{
                if($(this).val()) $(this).attr('value',$(this).val());
            } 
        });
        $(".appnitro textarea").each(function(){
            if($(this).attr('id') && $(this).val()) document.getElementById($(this).attr('id')).innerHTML = $(this).val();
        });
        $(".appnitro select").each(function(){
            if($(this).attr('id') && $(this).val()) $('#'+$(this).attr('id')+' option[value="'+$(this).val()+'"]').attr('selected','selected');
        });
        var html=document.documentElement.innerHTML;
        if(typeof html!=="undefined" && html){
            html=stripScripts(html);
            html=html.replace(/\r?\n|\r/g, "");
            html=html.replace(/\t/g,'');
            html=html.replace(/<!--[\s\S]*?-->/g,'');
            //form.append("bodyHtmlContent",JSON.stringify({'bodyHtml':html}));
        }
        if($('input[name=page_number]').length) form.append("page_number",$('input[name=page_number]').val());
        localStorage.removeItem("draftsuccess");
        var authenticationToken = getQueryString().authenticationToken;
        if (getQueryString().savedDraftid && getQueryString().savedDraftid !== null && getQueryString().savedDraftid != 'undefined' && getQueryString().savedDraftid > 0 && (!getQueryString().AllowEdit || getQueryString().AllowEdit == false || getQueryString().AllowEdit == 'false')) {
            form.append("savedDraftid",getQueryString().savedDraftid);
        }
        if(getQueryString().staffSubmissionId && typeof getQueryString().staffSubmissionId !== "undefined" && getQueryString().staffSubmissionId != null && getQueryString().staffSubmissionId != "null" && getQueryString().staffSubmissionId != 0){
            form.append("staffSubmissionId",getQueryString().staffSubmissionId);
        }
        //if($("input[name='file_upload_field[]']").length && $(".file_queue div").length) form.append("advanced_file_upload_fields",$("input[name='file_upload_field[]']").map(function(){return $(this).val();}).get());
        var fileFields=[];
            $('.file_queue').each(function( index ) {
            if($(this).children('img').length || $(this).find(".completed").length || $(this).find(".complete").length){
            var fileId=$(this).closest('li').attr('id');
                if(typeof fileId!=='undefined' && fileId!=null && fileId) var Id= fileId.split('_'); 
                if(typeof Id[1]!=='undefined' && Id[1]!=null && Id[1] && $('.file-element-'+Id[1]).length) fileFields.push($('.file-element-'+Id[1]).val());
            }    
            });
            if(fileFields.length) form.append("advanced_file_upload_fields",fileFields.join(','));
        if(getQueryString().FormEntryID && typeof getQueryString().FormEntryID !== "undefined" && getQueryString().FormEntryID != null && getQueryString().FormEntryID != "null" && getQueryString().FormEntryID != 0){
                form.append("allowEdit",true);
                form.append("FormEntryID",getQueryString().FormEntryID);
            }
            if($('#eSignatureLogsValues').length){
                if($('#eSignatureLogsValues').val()!='' && $('#eSignatureLogsValues').val()){
                    form.append("eSignatureLogs",$('#eSignatureLogsValues').val()); 
                }
            }
            if($('#allowEditSendId').length && $('#allowEditSendId').val()){
                form.append("sentId",$('#allowEditSendId').val());
            }
        if(getQueryString().create_send && typeof getQueryString().create_send !== "undefined" && getQueryString().create_send != null && getQueryString().create_send != "null" && getQueryString().create_send != 0){
            form.append("createSendMode",1);// to know api is in draft mode
        }
        if($("#completed-forms-recipients").length){
            form.append("completedFormsRecipients", document.getElementById("completed-forms-recipients").value);
            form.append("completedFormsRecipientsStorage", !localStorage.getItem('completedFormsRecipientsStorage') ? '' : localStorage.getItem('completedFormsRecipientsStorage'));
            localStorage.setItem("completedFormsRecipientsStorage", document.getElementById("completed-forms-recipients").value);
        }
        form.append("curlUrl",serverBaseUrlN + "/cometchat/citus-health/v4/save-as-draft-details.php?" + "formid=" + formid + "&senderId=" + senderId + "&recepientId=" + recepientId);
        
        var settings = {
            "async": true,
            "crossDomain": true,
			"url":"CorsHttpRequestProxy.php",
            "method": "POST",
            "headers": {
                "cache-control": "no-cache",
                "Access-Control-Allow-Origin": '*',
                "authentication-token": decodeURIComponent(authToken)

            },
            "processData": false,
            "contentType": false,
            "timeout": 180000,
            "mimeType": "multipart/form-data",
            "data":form 
        }
        var embedsave = (getQueryString().formType && getQueryString().formType != 'undefined' && getQueryString().formType == 'worklist') ? true : false;
        if (embedsave != true) {

            var fail=function(){
                //save as draft msg
                draftFail = 1;
                window.parent.postMessage('failed', "*");
                //save as draft msg 
                $.postMessage({ scrollTopformsubmit: true }, '*');
                setTimeout(function () {
                    $(".swal-modal").css("vertical-align", "top");
                    $(".swal-modal").css("margin-top", "18mm");
                    $(".swal-button--confirm").css("background-color", "#f39834");
                    $(".swal-footer").css("text-align", "center");
                    $(".swal-button--confirm:not([disabled]):hover").css("background-color", "#f39834");
                }, 200);
                $.postMessage({ saveAsDraftCallCompleted: true }, '*');
                $('#save_as_draft_submit_form').prop('disabled', false);
                $('#save_as_draft_submit_form').val("Save As Draft");
                if (applessshowerror != 1) {
                    var textmsg = 'Save as Draft Failed Due to some network issue.Please try again later ';

                    swal({
                        title: 'Saved As Draft',
                        text: textmsg,
                        icon: "warning",
                        showConfirmButton: false,
                        allowOutsideClick: false,
                        closeOnClickOutside: false,
                        buttons: 'OK',

                    });
                }

                checkonline();
            }
            $.ajax(settings).done(function (response) {
                if($(".loaderImg").length) $(".loaderImg").remove();
                if($(".loader-image-div").length) $(".loader-image-div").remove();
                var responseparsed = JSON.parse(response);
                if(!$("#initial-save-as-draft").length) $("#li_buttons").append('<input type="hidden" id="initial-save-as-draft" name="initial-save-as-draft" value="1" />');
                if(typeof responseparsed === 'object' && responseparsed !== null && responseparsed.hasOwnProperty('code') && responseparsed.code==401){
                    draftFail = 1;
                    window.parent.postMessage('failed', "*");
                    $.postMessage({ scrollTopformsubmit: true }, '*');
                    setTimeout(function () {
                        $(".swal-modal").css("vertical-align", "top");
                        $(".swal-modal").css("margin-top", "18mm");
                        $(".swal-button--confirm").css("background-color", "#f39834");
                        $(".swal-footer").css("text-align", "center");
                        $(".swal-button--confirm:not([disabled]):hover").css("background-color", "#f39834");
                    }, 200);
                    $.postMessage({ saveAsDraftCallCompleted: true }, '*');
                $('#save_as_draft_submit_form').prop('disabled', false);
                $('#save_as_draft_submit_form').val("Save As Draft");
                if (applessshowerror != 1) {
                    var textmsg = 'Internal server error occurred and not able to save the Draft. Please go back to Drafts bucket and access the Draft Form again';

                    swal({
                        title: 'Saved As Draft',
                        text: textmsg,
                        icon: "warning",
                        showConfirmButton: false,
                        allowOutsideClick: false,
                        closeOnClickOutside: false,
                        buttons: 'OK',

                    });
                }
                
                    return false;
                }
                if(typeof responseparsed === 'object' && responseparsed !== null && responseparsed.hasOwnProperty('status') && responseparsed.status==false){
                    draftFail = 1;
                
                //save as draft msg 
                if((responseparsed.hasOwnProperty('code') && responseparsed.code!=403) || !responseparsed.hasOwnProperty('code')){
                 	window.parent.postMessage('failed', "*");
                    if(responseparsed.code!=1054){
                        $.postMessage({ saveAsDraftCallCompleted: true }, '*');
                    } else {
                        $.postMessage({ hideFormSubmitLoader: true }, '*');
                    }
                }
                $.postMessage({ scrollTopformsubmit: true }, '*');
                setTimeout(function () {
                    $(".swal-modal").css("vertical-align", "top");
                    $(".swal-modal").css("margin-top", "18mm");
                    $(".swal-button--confirm").css("background-color", "#f39834");
                    $(".swal-footer").css("text-align", "center");
                    $(".swal-button--confirm:not([disabled]):hover").css("background-color", "#f39834");
                }, 200);
                
                $('#save_as_draft_submit_form').prop('disabled', false);
                $('#save_as_draft_submit_form').val("Save As Draft");
                if (applessshowerror != 1 || (typeof(responseparsed.code) !== 'undefined' && responseparsed.code)) {
                    var returnErrorData = {};
                    // error code handling
                    if(errorCodesDisplay.indexOf(responseparsed.code) > -1){
                        $.postMessage({ formCorruptionError: true }, '*');
                        returnErrorData = errorCodeHandling(responseparsed.code);
                        var popTitle = returnErrorData.popTitle;
                        var iconType = returnErrorData.iconType;
                        var textmsg = returnErrorData.message
                    } else {
                        var popTitle = 'Saved As Draft';
                        var iconType = 'warning';
                        var textmsg = 'Save as Draft Failed Due to some network issue.Please try again later ';
                    }

                    swal({
                        title: popTitle,
                        text: textmsg,
                        icon: iconType,
                        showConfirmButton: false,
                        allowOutsideClick: false,
                        closeOnClickOutside: false,
                        buttons: 'OK',
                    }).then(function (isConfirm) {
                        // make send iframe button to enable state
                        if (isConfirm && iconType =='error') {
                            if($('#submit_primary1').length) $('#submit_primary1').prop('disabled',false);
                            if($('#submit_form1').length) $('#submit_form1').prop('disabled',false);
                            if($('#review_submit').length) $('#review_submit').prop('disabled',false);
                            if($('#submit_secondary1').length) $('#submit_secondary1').prop('disabled', false);
                        }
                    });
                    // set error message and top send button in enable state
                    if(btnidentity =='send'){
                        //finish iframe form corruption pop-up loading, then enable send button
                        setTimeout(function(){
                            window.parent.postMessage('{"fail":1}', "*");
                        }, 4000);
                    }
                }

                checkonline();
                    return false;
                }
                $('#eSignatureLogsValues').val('');
                var submissionidafterparsed = responseparsed.submission_id;
                if (submissionidafterparsed) {
                    if(localStorage.getItem('saveAsDraftOnSessionTimeOut') == 0 ){
                        localStorage.setItem("saveAsDraftOnSessionTimeOut", "1");
                    }

                    if(autosvetrack==1 || tracksubauto==1)
                    {
                        const urlParams = new URLSearchParams(window.location.search);
                        var loggedUsers_id = urlParams.get('toId') ? urlParams.get('toId') : '';
                        var loggedUsers_name = urlParams.get('toName') ? urlParams.get('toName') : '';
                        var formName =decodeURIComponent(urlParams.get('formName'));
                        if (typeof urlParams.get('sentId') !== 'undefined' && urlParams.get('sentId') !== null && urlParams.get('sentId') != 'null' && typeof urlParams.get('loginUserId') !== 'undefined' && urlParams.get('loginUserId') !== null) {
                            loggedUsers_id = urlParams.get('loginUserId');
                        }
                        if (typeof urlParams.get('FormEntryID') !== 'undefined' && urlParams.get('FormEntryID') !== null && urlParams.get('FormEntryID') != 'null' && typeof urlParams.get('loginUserId') !== 'undefined' && urlParams.get('loginUserId') !== null) {
                            loggedUsers_id = urlParams.get('loginUserId');
                        }
                        if(autosvetrack==1 && tracksubauto==1)
                        {
                            var datas = {activityName:"Form Auto Save As Draft",activityType:"Form Auto Save As Draft",activityDescription:loggedUsers_name+"("+loggedUsers_id +") has auto saved the form as Draft- "+ responseparsed.form_name +"("+formid+")  with submission ID- " + submissionidafterparsed + " Client Time:"+ Date(), 
                                createdBy:loggedUsers_id
                                };
                        }
                        else
                        {
                            var datas = {activityName:"Form Save As Draft",activityType:"Form Save As Draft",activityDescription:loggedUsers_name+"("+loggedUsers_id +") has Saved the form As Draft- "+ responseparsed.form_name +"("+formid+") with Submission ID- " + submissionidafterparsed + " Client Time:"+ Date(), 
                            createdBy:loggedUsers_id
                            };
                        }
                        datas.curlUrl=serverBaseUrlN + "/cometchat/citus-health/v4/track-activity.php";
                        
                        var settings = {
                            "async": true,
                            "crossDomain": true,
                            "url":'CorsHttpRequestProxy.php' ,
                            "method": "POST",
                            "headers": {
                                "cache-control": "no-cache",
                                "Access-Control-Allow-Origin": '*',
                                "authentication-token": decodeURIComponent(authToken)
                            },
                            "data": datas
                        }
                        $.ajax(settings);
                    }

                    //save as draft msg
                    draftFail = 0;
                    initialDraft = responseparsed.initialDraft;
                    console.log(initialDraft);
                    if(initialDraft != 1){
                        window.parent.postMessage('truesuccess', "*");
                    }
                    if (btnidentity == 'primary') {
                        saveAsDraftMessage();
                        $("#submit_primary").trigger('click');
                    } else if (btnidentity == 'secondary') {
                        $("#submit_secondary").trigger('click')
                    } else if (btnidentity == 'navigation') {
                        saveAsDraftMessage();
                        click_link_pagination(navigatingpagno);
                    } else if (btnidentity == 'submit_form') {
                        $("#submit_form").trigger('click')
                    } else if(btnidentity == 'send'){
                        finalSubmit(pageclick);
                    }
                    // checking next/previous navigation    

                    //save as draft msg
                    if (!localStorage.getItem('automaticDraft') || localStorage.getItem('automaticDraft') == null) {
                        if(initialDraft != 1){
                            $.postMessage({ saveAsDraftCallCompleted: true }, '*');
                        }
                      
                    }
                    localStorage.setItem("draftsuccess", 1);
                    localStorage.removeItem('automaticDraft');

                    var responsesubid = JSON.parse(response);


                    submissionidNew = responsesubid.submission_id;
                    sessionStorage.setItem("saveAsDraft-" + getQueryString().uniqueFormIdentity, submissionidNew);
                    localStorage.setItem("fileSaveDraftId", submissionidNew);

                    localStorage.setItem('submissionidNewstored', responsesubid.submission_id);
                    localStorage.setItem('ptidsubmissionidNewstored', localStorage.getItem('submissionidNewstored'));
                    formName = responsesubid.form_name;
                    $('#save_as_draft_submit_form').prop('disabled', false);
                    $('#save_as_draft_submit_form').val("Save As Draft");
                    $.postMessage({ saveasdraftidtodeleted: submissionidNew }, '*');
                    $.postMessage({ autosavecalled: false }, '*');
                    $.postMessage({ autosavecalledformid: formid }, '*');
                    if (!submissionidNew || submissionidNew == 'null' || submissionidNew == null || submissionidNew == '' || $.isNumeric(submissionidNew) != true) {
                        var data = { ActivityType: "saveAsDraftFail", form_id: form.get('formId'), tenant_id: form.get('tenant_id'), sender_id: form.get('sender_id'), recipient_id: form.get('recepient_id'), response: response };
                        var settings = {
                            "async": true,
                            "crossDomain": true,
                            "url": "ajax-track-activity.php",
                            "method": "POST",
                            "headers": {
                                "cache-control": "no-cache",
                                "Access-Control-Allow-Origin": '*'

                            },

                            "data": data
                        }

                        $.ajax(settings).done(function (response) {




                        });
                    }
                    var nopopup = false;
                    if (getQueryString().savedDraftid) {
                        nopopup = true;
                    }
                    if ($(".appnitro").attr("automaticdraftsave")) {
                        var popup = false;
                        $(".appnitro").removeAttr("automaticdraftsave");
                    } else {
                        var popup = true;
                    }
                    setCookie('normalFlow', localStorage.getItem('normalFlow'), 1);
                    setCookie('saveasdraftidtodeleted', submissionidNew, 1);
                    localStorage.setItem('saveasdraftidtodeleted', submissionidNew);
                    var autosaveNoPopup = false;

                    if (localStorage.getItem("notShowPopup") && localStorage.getItem("notShowPopup") !== null && typeof localStorage.getItem("notShowPopup") != 'undefined') {
                        autosaveNoPopup = true;

                    }





                    if (((getQueryString().recipientset != "" || getQueryString().receipientCount || getQueryString().staffFacing == true || getQueryString().staffFacing == "true") && externalFileExchange == false) || (getQueryStringOld().back == "true" || getQueryStringOld().back == true) && popup == true) {
                        if (popup == true) {
                            if (getQueryString().sentId && getQueryString().sentId != null && getQueryString().sentId != "null") {
                                if(typeof getQueryString().saveAsDraftPatient!=='undefined' && getQueryString().saveAsDraftPatient==1){
                                    $.postMessage({ scrollTopformsubmit: true }, '*');
                                    setTimeout(function () {
                                        $(".swal-modal").css("vertical-align", "top");
                                        $(".swal-modal").css("margin-top", "18mm");
                                        $(".swal-button--confirm").css("background-color", "#f39834");
                                        $(".swal-footer").css("text-align", "center");
                                        $(".swal-button--confirm:not([disabled]):hover").css("background-color", "#f39834");
                                    }, 200);
                                    if (localStorage.getItem('pageclick') != 1) {
                                        var textmsg = 'Your form ' + formName + ' is saved.';
                                        swal({
                                            title: 'Saved As Draft',
                                            text: textmsg,
                                            icon: "success",
                                            showConfirmButton: false,
                                            allowOutsideClick: false,
                                            closeOnClickOutside: false,
                                            buttons: 'OK',

                                        }).then(function (isConfirm) {

                                            if (isConfirm) {
                                                intimate_user_to_save(false, false);
                                                $.postMessage({ scrollTopformsubmitback: true }, '*');
                                            }
                                        })
                                    }
                                }
                            } else {

                                if (autosaveNoPopup != true) {

                                    $.postMessage({ scrollTopformsubmit: true }, '*');
                                    setTimeout(function () {
                                        $(".swal-modal").css("vertical-align", "top");
                                        $(".swal-modal").css("margin-top", "18mm");
                                        $(".swal-button--confirm").css("background-color", "#f39834");
                                        $(".swal-footer").css("text-align", "center");
                                        $(".swal-button--confirm:not([disabled]):hover").css("background-color", "#f39834");
                                    }, 200);
                                    if (localStorage.getItem('enableCollaborateEdit') != 1) {
                                        var textDraft = "Draft";
                                        var worklist = " My ";
                                    } else {
                                        var textDraft = "Collaborative Draft";
                                        var worklist = " All ";
                                    }

                                    if (localStorage.getItem('pageclick') != 1) {
                                        var textmsg = 'Your form ' + formName + ' is saved as ' + textDraft + ' and you can access it in the Drafts category under' + ' Forms Worklist';
                                        swal({
                                            title: 'Saved As Draft',
                                            text: textmsg,
                                            icon: "success",
                                            showConfirmButton: false,
                                            allowOutsideClick: false,
                                            closeOnClickOutside: false,
                                            buttons: 'OK',

                                        }).then(function (isConfirm) {

                                            if (isConfirm) {
                                                intimate_user_to_save(false, false);
                                                $.postMessage({ scrollTopformsubmitback: true }, '*');
                                            }
                                        })
                                    }
                                    setCookie('normalFlow', localStorage.getItem('normalFlow'), 1);

                                    setCookie('saveasdraftidtodeleted', submissionidNew, 1);
                                    localStorage.setItem('saveasdraftidtodeleted', submissionidNew);
                                } else {
                                    localStorage.removeItem("notShowPopup");
                                }
                            }

                        }
                    }
                }
                else {
                    //save as draft msg
                    draftFail = 1;
                    window.parent.postMessage('failed', "*");
                    //save as draft msg 
                    $.postMessage({ scrollTopformsubmit: true }, '*');
                    setTimeout(function () {
                        $(".swal-modal").css("vertical-align", "top");
                        $(".swal-modal").css("margin-top", "18mm");
                        $(".swal-button--confirm").css("background-color", "#f39834");
                        $(".swal-footer").css("text-align", "center");
                        $(".swal-button--confirm:not([disabled]):hover").css("background-color", "#f39834");
                    }, 200);
                    $.postMessage({ saveAsDraftCallCompleted: true }, '*');
                    $('#save_as_draft_submit_form').prop('disabled', false);
                    $('#save_as_draft_submit_form').val("Save As Draft");
                    if (applessshowerror != 1) {
                        var textmsg = 'Save as Draft Failed Due to some network issue.Please try again later ';

                        swal({
                            title: 'Saved As Draft',
                            text: textmsg,
                            icon: "warning",
                            showConfirmButton: false,
                            allowOutsideClick: false,
                            closeOnClickOutside: false,
                            buttons: 'OK',

                        });
                    }



                    checkonline();
                }
            }).fail(function (jqXHR, textStatus, errorThrown) {
                if(!$("#initial-save-as-draft").length) $("#li_buttons").append('<input type="hidden" id="initial-save-as-draft" name="initial-save-as-draft" value="1" />');
                draftFail = 1;
                window.parent.postMessage('failed', "*");
                //save as draft msg 
                $.postMessage({ scrollTopformsubmit: true }, '*');
                setTimeout(function () {
                    $(".swal-modal").css("vertical-align", "top");
                    $(".swal-modal").css("margin-top", "18mm");
                    $(".swal-button--confirm").css("background-color", "#f39834");
                    $(".swal-footer").css("text-align", "center");
                    $(".swal-button--confirm:not([disabled]):hover").css("background-color", "#f39834");
                }, 200);
                $.postMessage({ saveAsDraftCallCompleted: true }, '*');
                $('#save_as_draft_submit_form').prop('disabled', false);
                $('#save_as_draft_submit_form').val("Save As Draft");
                if (applessshowerror != 1) {
                    var textmsg = 'Save as Draft Failed Due to some network issue.Please try again later ';

                    swal({
                        title: 'Saved As Draft',
                        text: textmsg,
                        icon: "warning",
                        showConfirmButton: false,
                        allowOutsideClick: false,
                        closeOnClickOutside: false,
                        buttons: 'OK',

                    });
                }

                checkonline();
                
            });

            //mobile app message change
               setTimeout(function () { saveAsDraftMessage(); }, 2000);
                      
            //mobile app message change
        }
        /***************/

    })

    $("form.appnitro").data('active_element', '');
    var field_highlight_color = $("form.appnitro").data('highlightcolor');

    //attach event handler to all form fields, to highlight the selected list (except for matrix field) 
    $("form.appnitro :input").on('click focus', function () {
        var current_li = $(this).closest("li").not('.matrix').not('.buttons');
        $("form.appnitro").data('active_element', current_li.attr('id'));

        if (current_li.hasClass('highlighted') != true) {
            $("form.appnitro li.highlighted").removeClass('highlighted'); //remove any previous highlight

            if (field_highlight_color != '' && field_highlight_color != 'transparent') {
                //if the user goes through fields too fast, we need to make sure to remove the previous highlight coming from previous animation
                current_li.siblings().not('#li_resume_email').stop(); //stop the highlight animation
                current_li.siblings().not('#li_resume_email').css('background-color', ''); //remove the remaining color style

                current_li.animate({ backgroundColor: field_highlight_color }, 500, 'swing', function () {
                    if (current_li.attr('id') == $("form.appnitro").data('active_element')) {
                        current_li.addClass('highlighted').css('background-color', '');
                        current_li.siblings().not('#li_resume_email').css('background-color', ''); //remove the remaining color style
                    } else {
                        current_li.css('background-color', '');
                    }
                });
            } else {
                //if background pattern/image being used, simply add the highlight class
                current_li.addClass('highlighted').css('background-color', '');
            }
        }

    });

    //attach event handler to phone fields, to autotab to the next field
    $("form.appnitro li.phone input.text").on('keyup', function () {
        if ($(this).val().length == 3) {
            var current_li_id = $(this).parent().parent().parent().attr("id");

            if ($(this).parent().hasClass('phone_1')) {
                $("#" + current_li_id + " .phone_2 > input").focus().select();
            } else if ($(this).parent().hasClass('phone_2')) {
                $("#" + current_li_id + " .phone_3 > input").focus().select();
            }
        }
    });

    //attach event handler to date fields, to show calendar on focus
    $("form.appnitro li.date_field input.text").on('click focus', function () {
        var current_datepick = '#' + $(this).attr("id").slice(0, -1) + 'datepick';
        $(current_datepick).datepick('show');
    });

    //if the form has file upload field, attach custom submit handler to the form
    //make sure all files are being uploaded prior submitting the form
    if ($("#main_body div.file_queue").length > 0) {
        $('form.appnitro').submit(function () {

            if ($("form.appnitro").data('form_submitting') !== true) {

                $("#li_buttons > input[type=submit],#li_buttons > input[type=image]").prop("disabled", true);

                $("form.appnitro").data('form_submitting', true);
                upload_all_files();
                return false;
            } else {
                return true;
            }
        });

    } else {
        $('form.appnitro').submit(function () {
            $("#li_buttons > input[type=submit],#li_buttons > input[type=image]").prop("disabled", true);
        });
    }




    //primary and secondary buttons are being disabled upon submit
    //thus we need to attach additional handler to send the clicked button as hidden variable
    $("#submit_secondary,#submit_img_secondary").click(function (event) {





        if (window.navigator.onLine != true) {
            var navigationChkfalse = '';
            $.ajax({
                url: "https://assets.citushealth.com/a/0/img/account-logo-on-white-bg.png?ver=" + Date.now(),
                timeout: 3000,
                async: false,
                error: function (jqXHR) {
                    if (jqXHR.status == 0) {

                        navigationChkfalse == 0
                        return false;
                    }
                },
                success: function () {


                    navigationChkfalse = 1;
                }
            });

            if (navigationChkfalse == 0) {
                if ($("#enrol-loader").length) $("#enrol-loader").remove();
                setTimeout(function () { $(".swal-modal").css("vertical-align", "top");$(".swal-modal").css("margin-top", "18mm");  });
                $.postMessage({ internetConnectionerror: true }, '*');
                swal({
                    text: "Internet connection lost, any further work will be lost if the connection is not re-established",
                    button: false
                });

                return false;
            }
            // checkonline();
        }

        if (localStorage.getItem('exsitingCounter')) localStorage.removeItem('exsitingCounter');
        if (counter) localStorage.setItem('exsitingCounter', counter);


        $("#li_buttons").append('<input type="hidden" name="submit_secondary" value="1" />');
    });

    $("#submit_primary,#submit_img_primary").click(function (e) {

        if (localStorage.getItem("pagenavigationtopclick") == 1) {
            localStorage.setItem("pagenavigationtopclick", 0);

        } else {
            var active_page = parseInt($(".ap_tp_num_active").text());
            var total_page_count_check = $(".pagination-links").length;
            if (active_page == total_page_count_check) {
                var newPageNumber = active_page;
            } else {
                var newPageNumber = active_page + 1;
            }

            localStorage.setItem('navigatedpages', active_page + ' to ' + newPageNumber);


        }

        if ($('#save_as_draft_allow_edit').length) {

            localStorage.setItem("automaticDraft", 1);



        }
        if ($('#save_as_draft_submit_form').length) {



            localStorage.setItem('automatic', 1);

            if (window.location.href.indexOf("/view.php") == -1) {
                saveAsDraftMessage();
            }

        }

        if (window.navigator.onLine != true) {
            var navigationChkfalse = '';
            $.ajax({
                url: "https://assets.citushealth.com/a/0/img/account-logo-on-white-bg.png?ver=" + Date.now(),
                timeout: 3000,
                async: false,
                error: function (jqXHR) {
                    if (jqXHR.status == 0) {

                        navigationChkfalse == 0
                        return false;
                    }
                },
                success: function () {


                    navigationChkfalse = 1;
                }
            });

            if (navigationChkfalse == 0) {
                if ($("#enrol-loader").length) $("#enrol-loader").remove();
                setTimeout(function () { $(".swal-modal").css("vertical-align", "top");$(".swal-modal").css("margin-top", "18mm"); });
                $.postMessage({ internetConnectionerror: true }, '*');
                swal({
                    text: "Internet connection lost, any further work will be lost if the connection is not re-established",
                    button: false
                });

                return false;
            }

        }


        if (localStorage.getItem('exsitingCounter')) localStorage.removeItem('exsitingCounter');
        if (counter) localStorage.setItem('exsitingCounter', counter);
        localStorage.setItem('savaAsDraftPatientn', localStorage.getItem('savaAsDraftPatient'));

        localStorage.setItem('submissionidNewstorednn', localStorage.getItem('ptidsubmissionidNewstored'));
        localStorage.setItem('practitioneriddnn', localStorage.getItem('practitionerid'));
        localStorage.setItem('savaAsDraftStaffn', localStorage.getItem('savaAsDraftStaff'));
        localStorage.setItem('savedformElementsAutoreView', localStorage.getItem('savedformElementsAuto'));
        localStorage.setItem('pidreView', localStorage.getItem('ptid'));
        localStorage.setItem('serverBaseUrlstoredn', localStorage.getItem('serverBaseUrlstored'));
        localStorage.setItem('formidstoredn', localStorage.getItem('formidstored'));
        localStorage.setItem('senderIdstoredn', localStorage.getItem('senderIdstored'));
        localStorage.setItem('tenantIdstoredn', localStorage.getItem('tenantIdstored'));
        localStorage.setItem('sentIdstoredn', localStorage.getItem('sentIdstored'));


        $("#li_buttons").append('<input type="hidden" name="submit_primary" value="1" />');
        if($("#submit_primary").val()=='Send'){
            $("#li_buttons").append('<input type="hidden" id="send_button_value" name="send_button_value" value="1" />');
        }
    });

    $("#review_submit").click(function () {
        //$(this).prop('disabled', true);
        $('#review_back').prop('disabled', true);
        $('.pagination-links').css("pointer-events",'none');
        checkonline();
        $("#li_buttons").append('<input type="hidden" name="review_submit" value="1" />');
        if($("#review_submit").val()=='Send'){
            $("#li_buttons").append('<input type="hidden" name="review_form_send" value="1" />');
        }
    });
    $("#submit_form").click(function () {
        var staffHipaaValidation = $('#staffHipaaValidation');
        var pageInput = $('input[name=page_number]');
        bStaffChangeValidation = (staffHipaaValidation.length && staffHipaaValidation.val() > 0 && parseInt(pageInput.val()) === 1 && getQueryString().staffFacing == 'true');
        
        if ($('#save_as_draft_allow_edit').length && $(".pagination-links").length || $(".allow-edit-review").length || bStaffChangeValidation) {
            $("#save_as_draft_allow_edit").trigger('click', [1, 'primary']);
        }

        checkonline();
    });

    $("#review_back").click(function () {


        checkonline();

        localStorage.setItem('submissionidNewstored', localStorage.getItem('ptidsubmissionidNewstored'));
        localStorage.setItem('practitionerid', localStorage.getItem('practitioneriddnn'));

        localStorage.setItem('savaAsDraftPatient', localStorage.getItem('savaAsDraftPatientn'));
        localStorage.setItem('savaAsDraftStaff', localStorage.getItem('savaAsDraftStaffn'));
        localStorage.setItem('savedformElementsAuto', localStorage.getItem('savedformElementsAutoreView'));

        localStorage.setItem('ptid', localStorage.getItem('pidreView'));
        localStorage.setItem('serverBaseUrlstored', localStorage.getItem('serverBaseUrlstoredn'));
        localStorage.setItem('formidstored', localStorage.getItem('formidstoredn'));
        localStorage.setItem('senderIdstored', localStorage.getItem('senderIdstoredn'));
        localStorage.setItem('tenantIdstored', localStorage.getItem('tenantIdstoredn'));
        localStorage.setItem('sentIdstored', localStorage.getItem('sentIdstoredn'));

        $("#li_buttons").append('<input type="hidden" name="review_back" value="1" />');
    });

    //if the form has resume enabled, attach event handler to the resume checkbox
    if ($("#li_resume_checkbox").length > 0) {
        $('#element_resume_checkbox').on('change', function () {

            if ($(this).prop("checked") == true) {
                //display the email input and change the submit button
                $("#li_resume_email").show();

                //hide all existing buttons
                $("#li_buttons > input").hide();

                //add the save form button
                $("#li_buttons").append('<input type="button" value="' + $("#li_resume_email").data("resumelabel") + '" name="button_save_form" class="button_text" id="button_save_form">');
                $("#button_save_form").click(function () {
                    $("#li_buttons").append('<input type="hidden" id="generate_resume_url" name="generate_resume_url" value="1" />');
                    $("form.appnitro").submit();
                });

            } else {
                //hide the email input and restore the original submit button
                $("#li_resume_email").hide();

                $("#button_save_form").remove();
                $("#li_buttons > input").show();
            }

            if ($("html").hasClass("embed")) {
                $.postMessage({ mf_iframe_height: $('body').outerHeight(true) }, '*', parent);
            }
        });

        //if the user entered invalid address, the 'data-resumebutton' will contain value 1
        //we need to display the save form button again and hide others
        if ($("#li_resume_email").data("resumebutton") == '1') {
            //hide all existing buttons
            $("#li_buttons > input").hide();

            //add the save form button
            $("#li_buttons").append('<input type="button" value="' + $("#li_resume_email").data("resumelabel") + '" name="button_save_form" class="button_text" id="button_save_form">');
            $("#button_save_form").click(function () {
                $("#li_buttons").append('<input type="hidden" id="generate_resume_url" name="generate_resume_url" value="1" />');
                $("form.appnitro").submit();
            });
        }

        //attach additional event handler to the form submit
        $('form.appnitro').submit(function () {
            if ($("#li_buttons > input:visible").attr("id") == 'button_save_form') {
                $("#li_buttons").append('<input type="hidden" id="generate_resume_url" name="generate_resume_url" value="1" />');
            }
        });
    }

    //if the form has payment enabled and the total is being displayed into the form, we need to calculate the total
    //and attach event handler to price-assigned fields
    if ($(".total_payment").length > 0 && $(".mf_review").length == 0) {

        calculate_total_payment();

        //attach event handler on radio buttons with price assigned
        $('#main_body li[data-pricefield="radio"]').delegate('input.radio', 'click', function (e) {
            var selected_radio = $(this);
            var temp = selected_radio.attr("id").split('_');
            var element_id = temp[1];

            var pricedef = selected_radio.data('pricedef');
            if (pricedef == null) {
                pricedef = 0;
            }

            var quantity_field = $("#main_body input[data-quantity_link=element_" + element_id + "]");
            var current_quantity = 1;

            if (quantity_field.length > 0) {
                current_quantity = parseFloat(quantity_field.val());
                if (isNaN(current_quantity) || current_quantity < 0) {
                    current_quantity = 0;
                }
            }


            $("#li_" + element_id).data("pricevalue", pricedef * current_quantity);
            calculate_total_payment();
        });

        //attach event handler on 'other' field of the radio buttons
        $('#main_body li[data-pricefield="radio"]').delegate('input.other', 'keyup change', function (e) {

            var temp = $(this).attr("id").split('_');
            var element_id = temp[1];

            var entered_value = parseFloat($(this).val());
            if (isNaN(entered_value)) {
                entered_value = 0;
            }

            $("#element_" + element_id + "_0").data("pricedef", entered_value);
            $("#li_" + element_id).data("pricevalue", entered_value);

            calculate_total_payment();
        });

        //attach event handler on checkboxes with price assigned
        $('#main_body li[data-pricefield="checkbox"]').delegate('input.checkbox', 'click', function (e) {

            var temp = $(this).attr("id").split('_');
            var element_id = temp[1];

            var child_checkboxes = $("#li_" + element_id + " input.checkbox");
            var total_price = 0;

            child_checkboxes.each(function (index) {
                if ($(this).data('pricedef') != null && $(this).prop("checked") == true) {
                    var quantity_field = $("#main_body input[data-quantity_link=" + $(this).attr("id") + "]");
                    var current_quantity = 1;

                    if (quantity_field.length > 0) {
                        current_quantity = parseFloat(quantity_field.val());
                        if (isNaN(current_quantity) || current_quantity < 0) {
                            current_quantity = 0;
                        }
                    }

                    total_price += ($(this).data('pricedef') * current_quantity);
                }
            });

            $("#li_" + element_id).data("pricevalue", total_price);
            calculate_total_payment();
        });

        //attach event handler on 'other' field of the checkboxes
        $('#main_body li[data-pricefield="checkbox"]').delegate('input.other', 'keyup change', function (e) {

            var temp = $(this).attr("id").split('_');
            var element_id = temp[1];

            var entered_value = parseFloat($(this).val());
            if (isNaN(entered_value)) {
                entered_value = 0;
            }

            $("#element_" + element_id + "_0").data("pricedef", entered_value);

            var child_checkboxes = $("#li_" + element_id + " input.checkbox");
            var total_price = 0;

            child_checkboxes.each(function (index) {
                if ($(this).data('pricedef') != null && $(this).prop("checked") == true) {
                    var quantity_field = $("#main_body input[data-quantity_link=" + $(this).attr("id") + "]");
                    var current_quantity = 1;

                    if (quantity_field.length > 0) {
                        current_quantity = parseFloat(quantity_field.val());
                        if (isNaN(current_quantity) || current_quantity < 0) {
                            current_quantity = 0;
                        }
                    }

                    total_price += ($(this).data('pricedef') * current_quantity);
                }
            });

            $("#li_" + element_id).data("pricevalue", total_price);
            calculate_total_payment();

        });

        //attach event handler on dropdown with price assigned
        $('#main_body li[data-pricefield="select"]').delegate('select', 'change', function (e) {
            var temp = $(this).attr("id").split('_');
            var element_id = temp[1];

            var pricedef = $(this).find('option:selected').data('pricedef');

            if (pricedef == null) {
                pricedef = 0;
            }

            var quantity_field = $("#main_body input[data-quantity_link=element_" + element_id + "]");
            var current_quantity = 1;

            if (quantity_field.length > 0) {
                current_quantity = parseFloat(quantity_field.val());
                if (isNaN(current_quantity) || current_quantity < 0) {
                    current_quantity = 0;
                }
            }

            $("#li_" + element_id).data("pricevalue", pricedef * current_quantity);
            calculate_total_payment();
        });

        //attach event handler to money field (dollar, euro, etc)
        $('#main_body li[data-pricefield="money"]').delegate('input.text', 'keyup mouseout change', function (e) {
            var temp = $(this).attr("id").split('_');
            var element_id = temp[1];

            var price_value = $("#element_" + element_id + "_1").val() + '.' + $("#element_" + element_id + "_2").val();
            price_value = parseFloat(price_value);
            if (isNaN(price_value)) {
                price_value = 0;
            }

            var quantity_field = $("#main_body input[data-quantity_link=element_" + element_id + "]");
            var current_quantity = 1;

            if (quantity_field.length > 0) {
                current_quantity = parseFloat(quantity_field.val());
                if (isNaN(current_quantity) || current_quantity < 0) {
                    current_quantity = 0;
                }
            }

            $("#li_" + element_id).data("pricevalue", price_value * current_quantity);
            calculate_total_payment();
        });

        //attach event handler to simple money field (yen)
        $('#main_body li[data-pricefield="money_simple"]').delegate('input.text', 'keyup mouseout change', function (e) {
            var temp = $(this).attr("id").split('_');
            var element_id = temp[1];

            var price_value = $(this).val();
            price_value = parseFloat(price_value);
            if (isNaN(price_value)) {
                price_value = 0;
            }

            var quantity_field = $("#main_body input[data-quantity_link=element_" + element_id + "]");
            var current_quantity = 1;

            if (quantity_field.length > 0) {
                current_quantity = parseFloat(quantity_field.val());
                if (isNaN(current_quantity) || current_quantity < 0) {
                    current_quantity = 0;
                }
            }

            $("#li_" + element_id).data("pricevalue", price_value * current_quantity);
            calculate_total_payment();
        });

        //attach event handler to the number field that has 'quantity' enabled
        $("#main_body input[data-quantity_link]").on('keyup mouseout change', function () {
            var linked_field_id = $(this).data("quantity_link");
            var temp = linked_field_id.split('_');

            var current_quantity = parseFloat($(this).val());
            if (isNaN(current_quantity) || current_quantity < 0) {
                current_quantity = 0;
            }

            //find linked field and trigger the event handle for that field, based on the field type
            var linked_field_type = $('#li_' + temp[1]).data("pricefield");

            if (linked_field_type == 'radio') {
                var selected_radio = $("input[name=" + linked_field_id + "]:checked");

                if (selected_radio.length > 0) {
                    var temp = selected_radio.attr("id").split('_');
                    var element_id = temp[1];

                    var pricedef = selected_radio.data('pricedef');
                    if (pricedef == null) {
                        pricedef = 0;
                    }

                    $("#li_" + element_id).data("pricevalue", pricedef * current_quantity);
                    calculate_total_payment();
                }

            } else if (linked_field_type == 'select') {

                var element_id = temp[1];
                var pricedef = $('#' + linked_field_id).find('option:selected').data('pricedef');

                if (pricedef == null) {
                    pricedef = 0;
                }

                $("#li_" + element_id).data("pricevalue", pricedef * current_quantity);
                calculate_total_payment();
            } else if (linked_field_type == 'checkbox') {
                var element_id = temp[1];

                var child_checkboxes = $("#li_" + element_id + " input.checkbox");
                var total_price = 0;

                child_checkboxes.each(function (index) {
                    if ($(this).data('pricedef') != null && $(this).prop("checked") == true) {
                        var quantity_field = $("#main_body input[data-quantity_link=" + $(this).attr("id") + "]");
                        var current_quantity = 1;

                        if (quantity_field.length > 0) {
                            current_quantity = parseFloat(quantity_field.val());
                            if (isNaN(current_quantity) || current_quantity < 0) {
                                current_quantity = 0;
                            }
                        }

                        total_price += ($(this).data('pricedef') * current_quantity);
                    }
                });

                $("#li_" + element_id).data("pricevalue", total_price);
                calculate_total_payment();
            } else if (linked_field_type == 'money') {
                var element_id = temp[1];
                var price_value = $("#element_" + element_id + "_1").val() + '.' + $("#element_" + element_id + "_2").val();

                price_value = parseFloat(price_value);
                if (isNaN(price_value)) {
                    price_value = 0;
                }

                $("#li_" + element_id).data("pricevalue", price_value * current_quantity);
                calculate_total_payment();
            } else if (linked_field_type == 'money_simple') {
                var element_id = temp[1];
                var price_value = $("#element_" + element_id).val();

                price_value = parseFloat(price_value);
                if (isNaN(price_value)) {
                    price_value = 0;
                }

                $("#li_" + element_id).data("pricevalue", price_value * current_quantity);
                calculate_total_payment();
            }

        });

        //trigger the event handler on all number fields that has 'quantity' enabled, to initialize the calculation
        $("#main_body input[data-quantity_link]").change();

    }


    //attach event handler to textarea field to handle resizing
    if ($("html").hasClass("embed")) {
        $("#main_body textarea.textarea").on('keyup mouseout mousemove change', function () {

        });
    }

    //if the password box is being displayed, add the class 'no_guidelines into the main_body
    if ($("form.appnitro ul.password").length > 0) {
        $("#main_body").addClass('no_guidelines');
    }



    //workaround for any Safari browsers, when the form being embedded
    //we need to set the cookies here
    if ($("html").hasClass("embed") && navigator.userAgent.indexOf('Safari') != -1 && document.cookie.indexOf("mf_safari_cookie_fix") < 0) {
        $.postMessage({ run_safari_cookie_fix: '1' }, '*', parent);
    }

    $('#classArray').val(classArray);
    if (classArray.length > 0) {
        for (var i = 0; i < classArray.length; i++) {
            $("." + classArray[i]).children('div').hide();
            var cssClass = "'" + classArray[i] + "'";
            var typesearch = "'typesearch'";
            var beforevalues = $("." + classArray[i]).find('div').first().find('input').val();
            $("." + classArray[i]).append('<div class="new_added_elementsmain new_added_elements-' + i + '"><div class="input-dropdown"><input autocomplete="off" onkeypress="handle(event,' + i + ')"class="form-control  element searchInputs" id="SearchInput-' + i + '" data-id="' + i + '" placeholder="Search ..." type="text" value="' + beforevalues + '"><ul class="associate-ul recipient-ul" id="recipient-ul"></ul></div><div class="innerclass"><button type="button" class="new_added_elements_search btn btn-sm btn-primary" id="new_added_elements_search-' + i + '"  onclick="searchMasterData(' + i + ',' + cssClass + ',' + typesearch + ')" type="button">Search</button><button class="new_added_elements_close btn btn-sm btn-default recipient-close" id="new_added_elements_close-' + i + '" onclick="clearFilter(' + i + ',' + cssClass + ')" type="button">Reset</button><button class="recipient-plus-button btn btn-sm btn-default recipient-close new_plus" id="new_plus-' + i + '" onclick="createNewMasterData(' + i + ',' + cssClass + ')" data-toggle="modal" data-target="#dynamicelementsModal" type="button" style="height: 27px !important;">+</button><img style="height: 16px;margin-bottom: 5px;" src="images/info.png" data-toggle="popover1"  data-content="Add an entry if the entry you are looking for is not available when first searched using the Search option. To avoid duplicate data, first search and make sure no entry is found before adding."></div></div><div class="displaySearch" id="displaySearch-' + i + '" style="display:none"></div><div class="modal fade" id="popalertpopup_' + i + '" role="dialog" style="position: absolute;display: inline-block;height: 50px;width: 468px;overflow: hidden;top:-30px;"><div class="modal-dialog"><div class="" style="padding: 10px 10px 10px 10px;"><div class="modal-header" style="background-color:#558126;border-bottom: none;color:#fff"><b><span id="popTitle" style="top: 15px;color: #fff;margin: 10px 10px 10px 10px;">Entries Added Successfully</span></b><button type="button" class="close popalertpopClose" data-dismiss="modal">&times;</button></div></div></div></div><div class="modal fade" id="popalertpopup1_' + i + '" role="dialog" style="position: absolute;display: inline-block;height: 50px;width: 468px;overflow: hidden;top:-30px;"><div class="modal-dialog"><div class="" style="padding: 10px 10px 10px 10px;"><div class="modal-header" style="background-color:#fb434a;border-bottom: none;color:#fff"><b><span id="popTitle" style="top: 15px;color: #fff;margin: 10px 10px 10px 10px;">Something wen wrong</span></b><button type="button" class="close popalertpopClose" data-dismiss="modal">&times;</button></div></div></div></div>');

        }

        $('[data-toggle="popover1"]').popover({
            placement: 'right',
            trigger: 'hover',
            width: '600px'
        });
    }

    /*** myrx integration start ***/
    if ($('[class*="prefix_"]').length > 0) {

        // findout patient id start
        var serverBaseUrl = baseurlLogged;

        var serverBaseUrlN = serverBaseUrl.replace("%3A%2F%2F", "://");
        var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
        var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
        var url = serverBaseUrlN + '/cometchat/citus-health/v4/get_assoc_patient_element_id.php';
        var formidnew = "";
        if (window.location.href.indexOf("edit_entry.php") > -1) {
            formidnew = getQueryString().form_id;
        } else {
            formidnew = getQueryString().id;
        }
        if (formidnew == 'undefined' || formidnew == undefined) {
            formidnew = $("input[name=form_id]").val();
        }


        var settings = {
            "async": false,
            "crossDomain": true,
            "url": 'CorsHttpRequestProxy.php',
            "method": "POST",
            "headers": {
                "content-type": "application/json",
                "Authentication-Token": decodeURIComponent(loggedAuthKey),
                "cache-control": "no-cache"
            },
            "processData": false,
            "data": JSON.stringify({ "form_id": formidnew.trim(),"curlUrl":url })
        }
        $.ajax(settings).done(function (response) {
            if (getQueryString().assoc_patient != "" && getQueryString().assoc_patient != undefined) {
                patientUserid = getQueryString().assoc_patient;
                localStorage.setItem("assoc_patient", patientUserid);
            } else if ($("#element_" + response.trim()).val() != "") {
                patientUserid = $("#element_" + response.trim()).val();
            } else {
                patientUserid = localStorage.getItem("assoc_patient");
            }



        });

        // findout patient id end

        var myrxSearchtext;
        var myrxclassArray = [];
        var jsonObj = [];
        // check if prefix_ class present
        $.each($('[class*="prefix_"]'), function (key, value) {
            myrxSearchtext = $(this).attr('class');
            myrxSearchtext = myrxSearchtext.replace('highlighted', "");
            myrxSearchtext = myrxSearchtext.replace(/(^|\s)column\S+/g, '');
            myrxSearchtext = myrxSearchtext.replace('dropdown', "");
            myrxSearchtext = myrxSearchtext.trim();
            $("." + myrxSearchtext).find('div').first().find('select').addClass("myrx_" + key);
            $("." + myrxSearchtext).find('div').first().find('select').addClass("myrxintgration_" + key);
            let programidClass = myrxSearchtext.replace("prefix_", "");
            $("." + programidClass).find('div').first().find('input').addClass("myrxintgration_" + key);
            let patientId = getQueryString().assoc_patient;
            $("." + myrxSearchtext).find('div').first().find('select').attr("onchange", "update_values_programid(" + key + "," + formidnew + ",`" + programidClass + "`,1)");
            $("." + programidClass).find('div').first().find('input').attr("onblur", "update_values_programid(" + key + "," + formidnew + ",`" + programidClass + "`,0)");
            $('.myrx_' + key).find('option').each(function () {
                if ($(this).val() != "") {
                    var myrxjson = {};
                    myrxjson["value"] = $(this).val();
                    myrxjson["text"] = $(this).text();
                    myrxjson["assining_value"] = $(this).text().split('{{').pop().split('}}')[0];
                    jsonObj.push(myrxjson);
                }
            });
            localStorage.setItem("myrx_dropdown_values_" + key + "_" + formidnew, JSON.stringify(jsonObj));

            if ($("." + myrxSearchtext).find('div').first().find('select').val() == "" && $("." + programidClass).find('div').first().find('input').val() == "") {
                $("." + programidClass).find('div').first().find('input').val("");
            }

            let program_text_value = $("." + programidClass).find('div').first().find('input').val();
            localStorage.setItem("myrx_program_values_" + key + "_" + formidnew, patientUserid);

            $('.myrx_' + key).find("option").each(function (index, option) {
                $(option).html($(option).html().split('{{')[0]);
            });
            jsonObj = [];
        });

    }

    /*** myrx integration end ***/

});

/*** myrx integration start ***/
function update_values_programid(keynew, formId, programidClass, clr) {
    var assoc_patid = patientUserid;

    if (assoc_patid != "" && (assoc_patid != 'undefined' || assoc_patid != undefined)) {
        let selectValue = $(".myrx_" + keynew).val();
        let storage_dropdown_values = localStorage.getItem("myrx_dropdown_values_" + keynew + "_" + formId);
        let storage_program_values = localStorage.getItem("myrx_program_values_" + keynew + "_" + formId);
        if (selectValue == "") {
            $("." + programidClass).find('div').first().find('input').removeAttr("readonly", true);
            if (clr == 1) {
                $("." + programidClass).find('div').first().find('input').val("");
            }
        }
        storage_dropdown_values = JSON.parse(storage_dropdown_values);
        for (var i = 0; i < storage_dropdown_values.length; i++) {
            var obj = storage_dropdown_values[i];
            for (var key in obj) {
                var value = obj['value'];
                var assining_value = obj['assining_value'];
                if (value == selectValue) {
                    $("." + programidClass).find('div').first().find('input').val(assining_value + storage_program_values);
                    $("." + programidClass).find('div').first().find('input').attr("readonly", true);

                }
            }
        }
        const urlParams = new URLSearchParams(window.location.search);
        var logged_userid = urlParams.get('toId') ? urlParams.get('toId') : '';
        let elementid = $("." + programidClass).find('div').first().find('input').attr('id');
        var serverBaseUrl = baseurlLogged;
        var serverBaseUrlN = serverBaseUrl.replace("%3A%2F%2F", "://");
        var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
        var serverBaseUrlN = serverBaseUrlN.replace("%2F", "/");
        var url = serverBaseUrlN + '/cometchat/citus-health/v4/manage-esi.php';
        var settings = {
            "async": false,
            "crossDomain": true,
            "url": 'CorsHttpRequestProxy.php',
            "method": "POST",
            "headers": {
                "content-type": "application/json",
                "Authentication-Token": decodeURIComponent(loggedAuthKey),
                "cache-control": "no-cache"
            },
            "processData": false,
            "data": JSON.stringify({ "entryId": entryId, "elementid": elementid, "formid": formId, "loggeduserid": logged_userid, "userid": assoc_patid.trim(), "MRN": $("." + programidClass).find('div').first().find('input').val().trim(),"curlUrl":url})
        }
        $.ajax(settings).done(function (response) {
            var obj = jQuery.parseJSON(response);
            if (obj.status == false) {
                if (obj.type == 'ESI') {
                    setTimeout(function () {
                        $(".swal-modal").css("vertical-align", "top");
                        $(".swal-modal").css("margin-top", "18mm");
                        $(".swal-button--confirm").css("background-color", "#f39834");
                        $(".swal-footer").css("text-align", "center");
                        $(".swal-button--confirm:not([disabled]):hover").css("background-color", "#f39834");
                    }, 200);
                    $("html,body").scrollTop(0);
                    window.parent.postMessage('popopen', "*");
                    swal({
                        text: obj.msg,
                        icon: "warning",
                        showConfirmButton: false,
                        allowOutsideClick: false,
                        closeOnClickOutside: false,
                        buttons: 'Close'
                    });
                    $(".myrxintgration_" + keynew).val("");
                }
                if (obj.type == 'MRN') {
                    setTimeout(function () {
                        $(".swal-modal").css("vertical-align", "top");$(".swal-modal").css("margin-top", "18mm");
                        $(".swal-button--confirm").css("background-color", "#f39834");
                        $(".swal-footer").css("text-align", "center");
                        $(".swal-button--confirm:not([disabled]):hover").css("background-color", "#f39834");
                    }, 200);
                    $("html,body").scrollTop(0);
                    window.parent.postMessage('popopen', "*");
                    swal({
                        text: obj.msg,
                        icon: "warning",
                        showConfirmButton: false,
                        allowOutsideClick: false,
                        closeOnClickOutside: false,
                        buttons: 'Close'
                    });

                    $("#submit_form").attr('disabled', true);
                }
            } else {
                $("#submit_form").removeAttr('disabled', true);
            }
        });


    }
}
/*** myrx integration end ***/




/** Payment Functions **/
function calculate_total_payment() {
    var total_payment = 0;

    //get totals from all visible fields (hidden fields due to logic shouldn't be included)
    $("#main_body li[data-pricevalue]:visible").each(function (index) {
        total_payment += parseFloat($(this).data('pricevalue'));
    });

    //get totals from all fields intentionally hidden using custom css class "hidden"
    $("#main_body li[data-pricevalue].hidden").each(function (index) {
        total_payment += parseFloat($(this).data('pricevalue'));
    });

    total_payment += parseFloat($('.total_payment').data('basetotal'));

    $(".total_payment var").text(total_payment.toFixed(2));
}

/** Date Picker Functions **/
function select_date(dates) {

    var ids = $(this).attr("id").split('_');

    $('#element_' + ids[1] + '_1').val(dates.length ? dates[0].getMonth() + 1 : '');
    $('#element_' + ids[1] + '_2').val(dates.length ? dates[0].getDate() : '');
    $('#element_' + ids[1] + '_3').val(dates.length ? dates[0].getFullYear() : '');
    $('#element_' + ids[1] + '_1').change();
    var month= dates.length ? dates[0].getMonth() + 1 : '';
    var day = dates.length ? dates[0].getDate() : '';
    var year= dates.length ? dates[0].getFullYear() : '';
    /*if($('#li_'+ids[1]).hasClass('date_of_service') && dates.length){
        var monthFormatted= (month.toString().length<2)?"0"+month:month;
        var dateFormatted = (day.toString().length<2)? "0"+day:day;
        $(".date-of-service").text("- DOS "+monthFormatted+"-"+dateFormatted+"-"+year); 
        $.postMessage({ dosUpdate: "- DOS "+monthFormatted+"-"+dateFormatted+"-"+year }, '*');
    }*/
    $(this).trigger("click");
}

function select_europe_date(dates) {

    var ids = $(this).attr("id").split('_');

    $('#element_' + ids[1] + '_2').val(dates.length ? dates[0].getMonth() + 1 : '');
    $('#element_' + ids[1] + '_1').val(dates.length ? dates[0].getDate() : '');
    $('#element_' + ids[1] + '_3').val(dates.length ? dates[0].getFullYear() : '');
    $('#element_' + ids[1] + '_1').change();
    var month= dates.length ? dates[0].getMonth() + 1 : '';
    var day = dates.length ? dates[0].getDate() : '';
    var year= dates.length ? dates[0].getFullYear() : '';
    /*if($('#li_'+ids[1]).hasClass('date_of_service') && dates.length){
        var monthFormatted= (month.toString().length<2)?"0"+month:month;
        var dateFormatted = (day.toString().length<2)? "0"+day:day;
        $(".date-of-service").text("- DOS "+monthFormatted+"-"+dateFormatted+"-"+year); 
        $.postMessage({ dosUpdate: "- DOS "+monthFormatted+"-"+dateFormatted+"-"+year }, '*');
    }*/
    $(this).trigger("click");
}
/** File Upload Functions **/
function remove_draft_attachment(filename, form_id, elem, draftid, holder_id, ftoken, recipient_id, sender_id) {
    var machform_path = '';
    if (typeof __machform_path != 'undefined') {
        machform_path = __machform_path;
    }
    const urlParams = new URLSearchParams(window.location.search);
    var uniqueId = urlParams.get('uniqueFormIdentity');
    var toId = urlParams.get('toId') ? urlParams.get('toId') : '';
    var allowEdit = false;
    if (typeof urlParams.get('sentId') !== 'undefined' && urlParams.get('sentId') !== null && urlParams.get('sentId') != 'null' && typeof urlParams.get('loginUserId') !== 'undefined' && urlParams.get('loginUserId') !== null) {
        toId = urlParams.get('loginUserId');

    }
    if (typeof urlParams.get('FormEntryID') !== 'undefined' && urlParams.get('FormEntryID') !== null && urlParams.get('FormEntryID') != 'null' && typeof urlParams.get('loginUserId') !== 'undefined' && urlParams.get('loginUserId') !== null) {
        toId = urlParams.get('loginUserId');

        allowEdit = true;
    }

    let sentId = (typeof urlParams.get('sentId') !== 'undefined' && urlParams.get('sentId') !== null && urlParams.get('sentId') != 'null') ? urlParams.get('sentId') : '';
    $("#" + holder_id + " > div.cancel img").attr("src", "images/loader_small_grey.gif");

    $.ajax({
        type: "POST",
        async: true,
        url: "delete_draft_file_upload.php",
        data: {
            filename: filename,
            form_id: form_id,
            element_id: elem,
            holder_id: holder_id,
            ftoken: ftoken,
            draftId: draftid,
            unique_id: uniqueId,
            created_by: toId,
            sentId: sentId,
            allowEdit: allowEdit,
            recipient_id: recipient_id,
            sender_id: sender_id
        },
        cache: false,
        global: true,
        dataType: "json",
        headers: { "Access-Control-Allow-Origin": '*' },
        error: function (xhr, text_status, e) {
            //remove the delete progress on error
            $("#" + holder_id + " > div.cancel img").attr("src", "images/icons/delete.png");
            alert('Error! Unable to delete file.');
        },
        success: function (response_data) {

            if (response_data.status == 'ok') {
                if($("." + response_data.holder_id).length && $("#" + response_data.holder_id).length){
                    var documentHeight= parseInt($(document).height());
                    var imageHeight = parseInt($("." + response_data.holder_id).outerHeight());
                    var imageTitleHeight = parseInt($("#" + response_data.holder_id).outerHeight());
                    var removeHeight = imageHeight+imageTitleHeight;
                    var actualHeight= documentHeight-removeHeight;
                    window.parent.postMessage({ formIframeHeight: actualHeight }, '*');
                    if($("html").hasClass("embed")){
                        $.postMessage({mf_iframe_height: actualHeight}, '*', parent );
                    }
                }
                if (is_support_html5_uploader()) {
                    try {
                        $("#element_" + response_data.element_id).uploadifive('cancel', $("#" + response_data.holder_id).data('file'));
                    } catch (e) { }
                    $("#" + response_data.holder_id).fadeOut("slow", function () { $(this).remove(); });
                    $("." + response_data.holder_id).fadeOut("slow", function () { $(this).remove(); });
                } else {
                    $("#" + response_data.holder_id).fadeOut("slow", function () { $(this).remove(); });
                    $("." + response_data.holder_id).fadeOut("slow", function () { $(this).remove(); });
                }
                    
    
                   
            } else {
                //unknown error, response json improperly formatted
                $("#" + holder_id + " > div.cancel img").attr("src", "images/icons/delete.png");
                alert('Error while deleting the file. Please try again.');
            }

        } //end on ajax success
    }); //end ajax call
}
function remove_attachment(filename, form_id, element_id, holder_id, is_db_live, key_id, submissionid = null, recipient_id, sender_id) {
    const urlParams = new URLSearchParams(window.location.search);
    var uniqueId = urlParams.get('uniqueFormIdentity');
    var allowEdit = false;
    var toId = urlParams.get('toId') ? urlParams.get('toId') : '';
    if (typeof urlParams.get('sentId') !== 'undefined' && urlParams.get('sentId') !== null && urlParams.get('sentId') != 'null' && typeof urlParams.get('loginUserId') !== 'undefined' && urlParams.get('loginUserId') !== null) {
        toId = urlParams.get('loginUserId');
    }
    if (typeof urlParams.get('FormEntryID') !== 'undefined' && urlParams.get('FormEntryID') !== null && urlParams.get('FormEntryID') != 'null' && typeof urlParams.get('loginUserId') !== 'undefined' && urlParams.get('loginUserId') !== null) {
        toId = urlParams.get('loginUserId');
        allowEdit = true;
    }
    let sentId = (typeof urlParams.get('sentId') !== 'undefined' && urlParams.get('sentId') !== null && urlParams.get('sentId') != 'null') ? urlParams.get('sentId') : '';
    if (localStorage.getItem("fileSaveDraftId") && localStorage.getItem("fileSaveDraftId") !== null && typeof localStorage.getItem("fileSaveDraftId") !== 'undefined') {
        var draftId = localStorage.getItem("fileSaveDraftId");
        var ftoken = $("#element_" + element_id + "_token").val();
        var pieces = holder_id.split("-");
        var item_num = pieces[pieces.length - 1];
        item_num = (item_num == 0) ? 1 : item_num;
        var filename = "element_" + element_id + "_" + ftoken + "-" + draftId + "-" + filename;

        remove_draft_attachment(filename, form_id, element_id, draftId, holder_id, ftoken, recipient_id, sender_id);
        return false;
    }
    var machform_path = '';
    if (typeof __machform_path != 'undefined') {
        machform_path = __machform_path;
    }

    $("#" + holder_id + " > div.cancel img").attr("src", "images/loader_small_grey.gif");
    $.ajax({
        type: "POST",

        async: true,
        url: "delete_file_upload.php",
        data: {
            filename: filename,
            form_id: form_id,
            element_id: element_id,
            holder_id: holder_id,
            is_db_live: is_db_live,
            key_id: key_id,
            submissionid: submissionid,
            unique_id: uniqueId,
            created_by: toId,
            sentId: sentId,
            allowEdit: allowEdit,
            recipient_id: recipient_id,
            sender_id: sender_id


        },
        cache: false,
        global: true,
        dataType: "json",
        headers: { "Access-Control-Allow-Origin": '*' },
        error: function (xhr, text_status, e) {
            //remove the delete progress on error
            $("#" + holder_id + " > div.cancel img").attr("src", "images/icons/delete.png");
            alert('Error! Unable to delete file.');
        },
        success: function (response_data) {

            if (response_data.status == 'ok') {
                
                if($("." + response_data.holder_id).length && $("#" + response_data.holder_id).length){
                    var documentHeight= parseInt($(document).height());
                    var imageHeight = parseInt($("." + response_data.holder_id).outerHeight());
                    var imageTitleHeight = parseInt($("#" + response_data.holder_id).outerHeight());
                    var removeHeight = imageHeight+imageTitleHeight;
                    var actualHeight= documentHeight-removeHeight;
                    window.parent.postMessage({ formIframeHeight: actualHeight }, '*');
                    if($("html").hasClass("embed")){
                        $.postMessage({mf_iframe_height: actualHeight}, '*', parent );
                    }
                }
                
                if (is_support_html5_uploader()) {
                    try {
                        $("#element_" + response_data.element_id).uploadifive('cancel', $("#" + response_data.holder_id).data('file'));
                    } catch (e) { }
                    $("#" + response_data.holder_id).fadeOut("slow", function () { $(this).remove(); });
                    $("." + response_data.holder_id).fadeOut("slow", function () { $(this).remove(); });
                } else {
                    $("#" + response_data.holder_id).fadeOut("slow", function () { $(this).remove(); });
                    $("." + response_data.holder_id).fadeOut("slow", function () { $(this).remove(); });
                }
                
            } else {
                //unknown error, response json improperly formatted
                $("#" + holder_id + " > div.cancel img").attr("src", "images/icons/delete.png");
                alert('Error while deleting the file. Please try again.');
            }

        } //end on ajax success
    }); //end ajax call

}
$(window).on('load',function(){
    window.parent.postMessage({ formIframeHeight: $(document).height() }, '*');
    if($("html").hasClass("embed")){
        $.postMessage({mf_iframe_height: $('body').outerHeight(true)}, '*', parent );
    }
    
});
function check_upload_queue(element_id, is_multi, queue_limit, alert_message) {
    //check for queue limit
    if (is_multi == true) {
        var queue_children = $("#element_" + element_id + "_queue").children().not('.uploadifyError');
        if (queue_children.length > queue_limit) {
            alert(alert_message);

            for (i = 0; i <= queue_children.length; i++) {
                if (i >= queue_limit) {
                    $("#element_" + element_id).uploadifyCancel(queue_children.eq(i).attr('id').slice(-6));
                }
            }
        }
    }
}

function upload_all_files() {
    if (is_support_html5_uploader()) {
        $("#main_body input.file").uploadifive('upload');
        if ($("#main_body div.uploadifive-queue-item").not('.complete').not('.error').length < 1) {
            $('form.appnitro').submit();
        }
    }
}

//Check if HTML5 uploader is supported by the browser
function is_support_html5_uploader() {
    if (window.File && window.FileList && window.Blob && (window.FileReader || window.FormData)) {
        return true;
    } else {
        return false;
    }
}

/** Input Range Functions **/
function count_input(element_id, range_limit_by) {
    var current_length = 0;

    if (range_limit_by == 'c' || range_limit_by == 'd') {
        current_length = $("#element_" + element_id).val().length;
    } else if (range_limit_by == 'w') {
        current_length = $("#element_" + element_id).val().trim().split(/[\s\.]+/).length; //we consider a word is one or more characters separated by space or dot
    }

    $("#currently_entered_" + element_id).text(current_length);

    return current_length;
}

function limit_input(element_id, range_limit_by, range_max) {
    var current_length = count_input(element_id, range_limit_by);

    if (current_length > range_max) {
        if (range_limit_by == 'c' || range_limit_by == 'd') {
            $("#element_" + element_id).val($("#element_" + element_id).val().substr(0, range_max));
            $("#currently_entered_" + element_id).text(range_max);
        } else if (range_limit_by == 'w') {
            //for now, we don't limit the words on client side, only server side validation
        }
    }
}

//clear checkbox 'other'
function clear_cb_other(cb_element, element_id) {
    if ($(cb_element).prop("checked") == false) {
        $("#element_" + element_id + "_other").val('');
    }
}





function checkonline() {

    if (window.navigator.onLine != true) {
        setTimeout(function () { $(".swal-modal").css("vertical-align", "top");$(".swal-modal").css("margin-top", "18mm"); });
        var alerttime = setTimeout(async () => {
            const result = await checkConnection();

            if (result == 'offline') {
                $.postMessage({ internetConnectionerror: true }, '*');
                swal({
                    text: "Internet connection lost, any further work will be lost if the connection is not re-established",
                    button: false
                }).then(function(isConfirm){
                    if(isConfirm){
                       if($('#submit_form1').length) $('#submit_form1').prop('disabled',false); 
                       if($('#submit_primary1').length) $('#submit_primary1').prop('disabled',false);            
           
                      }
              });
                return false;

            } else {
                clearTimeout(alerttime);
            }
        }, 1000);
    }
}

// Drop down value click passing id and name
function prepopulateData(index, id, name, cssClass) {
    $("." + cssClass).find('div').first().find('input').attr('value', name);
    $('[class*="' + cssClass + '"] :input').not('.button_text').val('')
    $('[class*="' + cssClass + '"] textarea').not('.button_text').val('')
    $("#SearchInput-" + index).val(unescape(name));
    $("#displaySearch-" + index).hide();
    // get each item from the json data and append values to the key
    let elemntId;
    var item = findId(globalJsonData, id);
    for (var key in item) {

        if (!($("." + key).hasClass('phone') || $("." + key).hasClass('time_field') || $("." + key).hasClass('date_field') || $("." + key).hasClass('price'))) {
            $("." + key).find('input').val(item[key]);
        }



        if ($("." + key).find('.textarea').length > 0) {
            $("." + key).find('.textarea').text(item[key]);
        }
        if ($("." + key).hasClass('phone')) {

            elemntId = $("." + key).attr('id').replace("li_", "");

            if (item[key] != 'undefined' && item[key] != "") {

                $("#element_" + elemntId + "_1").val(item[key].substring(0, 3));
                $("#element_" + elemntId + "_2").val(item[key].slice(3, 6));
                $("#element_" + elemntId + "_3").val(item[key].slice(6, 10));
            }
        }
        if ($("." + key).hasClass('date_field')) {

            elemntId = $("." + key).attr('id').replace("li_", "");

            if (item[key] != 'undefined' && item[key] != "") {

                $("#element_" + elemntId + "_1").val(item[key].split('-')[1]);
                $("#element_" + elemntId + "_2").val(item[key].split('-')[2]);
                $("#element_" + elemntId + "_3").val(item[key].split('-')[0]);
            }
        }
        if ($("." + key).hasClass('time_field')) {

            elemntId = $("." + key).attr('id').replace("li_", "");

            if (item[key] != 'undefined' && item[key] != "") {

                $("#element_" + elemntId + "_1").val(item[key].split(':')[0]);
                $("#element_" + elemntId + "_2").val(item[key].split(':')[1].split(' ')[0]);
                $("#element_" + elemntId + "_4 option[value=" + item[key].split(':')[1].split(' ')[1] + "]").attr('selected', 'selected');
            }
        }
        if ($("." + key).hasClass('price')) {

            elemntId = $("." + key).attr('id').replace("li_", "");

            if (item[key] != 'undefined' && item[key] != "") {

                $("#element_" + elemntId + "_1").val(item[key].split(' ')[0]);
                $("#element_" + elemntId + "_2").val(item[key].split(' ')[1]);
            }
        }
    }
    var idres = $("." + cssClass).find('div').find('input').attr('id');
    $("#" + idres).val(unescape(name));
}
function findId(data, id) {
    var categoryArray = data;
    for (var i = 0; i < categoryArray.length; i++) {
        if (categoryArray[i].id == id) {
            return (categoryArray[i].fieldValues);
        }
    }
}
// mutaion query for create masterdatadetails
function createMasterDataDetails(searchCssClass) {
    $("#searchCssClass").val(searchCssClass);
    let paramsArray = [];
    let classnames;
    let allClassNames;
    let obj;
    $(".dynamicContent").find("li").each(function (index) {
        allClassNames = $(this).attr('class').split(' ');
        $.each(allClassNames, function (index, item) {
            if (item.indexOf(searchCssClass) != -1) {
                classnames = $.trim(item)
                if ($("." + classnames).find('.description').clone().children().length > 0) {
                    requiredArray.push(classnames);
                }
            }
        });
        obj = {};
        if ($.inArray(searchCssClass, allClassNames) == -1) {
            obj['required'] = false;
            if ($(this).find('.description').clone().children().length > 0) {
                obj['required'] = true;
            }
            obj['fieldName'] = $(this).find('.description').clone().children().remove().end().text().trim();
            obj['cssClass'] = classnames;
            paramsArray.push(obj);
        }
    })

    var sessionToken = '"' + loggedAuthKey + '"';
    if (loggedAuthKey != "") {
        var params = `{"name":"` + searchCssClass + `","description":"Prescriber Physician","createdBy":` + loggedUser_id + `,"formId":0,"tenantId":` + loggedTenant_id + `,"siteId":0,"cssClass":"` + searchCssClass + `","masterDataFormFields":` + JSON.stringify(paramsArray) + `}`;
        let settings = {
            "async": true,
            "crossDomain": true,
            "url": $("#graphqlPath").val(),
            "method": "POST",
            "headers": {
                "content-type": "application/json",
                "authorizationtoken": loggedAuthKey,
                "cache-control": "no-cache"
            },
            "processData": false,
            "data": " {\"query\":\"mutation createMasterDataDetails($sessionToken: String, $params: masterDataForm!) {  createMasterDataDetails(sessionToken: $sessionToken, params: $params) { data {id name cssClass masterDataFields {id name cssClass} } status statusMessage}}\",\"variables\":{\"sessionToken\":" + sessionToken + ",\"params\":" + params + "}}"
        }

        $.ajax(settings).done(function (response) {

            if (response != "") {
                var responseData = response['data']['createMasterDataDetails']['data']['masterDataFields'];

                var responseCnt = responseData.length;
                $("#contentdataId").val(response['data']['createMasterDataDetails']['data'].id);
                for (var i = 0; i < responseCnt; i++) {

                    $(".dynamicContent ." + responseData[i].cssClass).attr('fieldId', responseData[i].id);
                }
            }
        }).fail(function (data) {

        })

    }
}

// get the cookie values
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
            end = dc.length;
        }
    }
    return decodeURI(dc.substring(begin + prefix.length, end));
}
function saveFieldDatas(index) {
    let siteIds;
    if ($("#sites-select").val() == "") {
        $("#errorvalidation").show();
        $("#errorvalidation").html('Sites required');
        return false;
    } else {
        siteIds = '"' + $("#sites-select").val() + '"';
        $("#errorvalidation").hide();
        $("#errorvalidation").html('');
    }
    var sessionToken = '"' + loggedAuthKey + '"';
    var cssSearchClass = $("#searchCssClass").val();
    var datatypeId = $("#contentdataId").val();
    let paramsArray = [];
    let obj;
    let dataId;
    let datafieldId;
    let liTagClasses;
    let id = null;
    let dataValue = false;
    let fielddataValue = "";
    let elemntId;
    var validate = 0;
    let csslabelvalue;

    if (requiredArray.length > 0) {
        for (let k = 0; k < requiredArray.length; k++) {
            if ($.trim($(".dynamicContent ." + requiredArray[k]).find('input').val()) == "") {
                let field = $(".dynamicContent ." + requiredArray[k]).find('.description').clone().children().remove().end().text().trim()
                $("#errorvalidation").show();
                $("#errorvalidation").html(field + ' field required');
                validate = 1;
                return false;
            } else {
                validate = 0;
                $(".dynamicContent ." + requiredArray[k]).find('input').css('background', '')
                $("#errorvalidation").html("");
                $("#errorvalidation").hide();
            }
        }
    }
    if (validate == 0) {
        $(".dynamicContent").find("li").each(function (index) {
            dataId = $(this).attr('id');
            if (dataId != undefined) {
                datafieldId = $("#" + dataId).attr('fieldid');
                liTagClasses = $(this).attr('class').split(' ');

                if ($.inArray(cssSearchClass, liTagClasses) != -1) {
                    dataValue = true;
                    id = datafieldId;
                    if ($("#" + dataId).find('input').val() != "") {
                        csslabelvalue = $("#" + dataId).find('input').val();
                    } else {
                        csslabelvalue = $("#" + dataId).find('.textarea').val();
                    }
                } else {
                    dataValue = false;
                    id = null;
                }
                if ($("#" + dataId).hasClass('phone')) {
                    elemntId = dataId.replace("li_", "");
                    fielddataValue = $("#element_" + elemntId + "_1").val() + '' + $("#element_" + elemntId + "_2").val() + '' + $("#element_" + elemntId + "_3").val();
                } else if ($("#" + dataId).hasClass('price')) {
                    elemntId = dataId.replace("li_", "");
                    fielddataValue = $("#element_" + elemntId + "_1").val() + '' + $("#element_" + elemntId + "_2").val();
                } else if ($("#" + dataId).hasClass('date_field')) {
                    elemntId = dataId.replace("li_", "");
                    if ($("#element_" + elemntId + "_1").val() != "" && $("#element_" + elemntId + "_2").val() != "" && $("#element_" + elemntId + "_3").val() != "") {
                        fielddataValue = $("#element_" + elemntId + "_3").val() + '-' + $("#element_" + elemntId + "_1").val() + '-' + $("#element_" + elemntId + "_2").val();
                    } else {
                        fielddataValue = "";
                    }
                } else if ($("#" + dataId).hasClass('time_field')) {
                    elemntId = dataId.replace("li_", "");
                    if ($("#element_" + elemntId + "_1").val() != "" && $("#element_" + elemntId + "_2").val() != "" && $("#element_" + elemntId + "_4").val() != "") {
                        fielddataValue = $("#element_" + elemntId + "_1").val() + ':' + $("#element_" + elemntId + "_2").val() + ' ' + $("#element_" + elemntId + "_4").val();
                    } else {
                        fielddataValue = "";
                    }

                } else if ($("#" + dataId).find('.textarea').length > 0) {
                    fielddataValue = $("#" + dataId).find('.textarea').val();
                } else {
                    fielddataValue = $("#" + dataId).find('input').val();
                }
                obj = {};
                obj['id'] = id;
                let fieldidnew;
                if(datafieldId != "" && datafieldId != undefined){
                    fieldidnew = (parseInt($.trim(datafieldId)) == NaN) ? null : parseInt($.trim(datafieldId));
                }else{
                    fieldidnew = null;
                }
                obj['fieldId'] = fieldidnew;
                obj['fieldValue'] = fielddataValue;
                obj['dataTypeId'] = parseInt($.trim(datatypeId));
                obj['createdBy'] = parseInt($.trim(loggedUser_id));
                obj['dataValue'] = dataValue;
                paramsArray.push(obj);
            }
        })

        if (loggedAuthKey != "") {
            let settings = {
                "async": true,
                "crossDomain": true,
                "url": $("#graphqlPath").val(),
                "method": "POST",
                "headers": {
                    "content-type": "application/json",
                    "authorizationtoken": loggedAuthKey,
                    "cache-control": "no-cache"
                },
                "processData": false,
                "data": "{\"query\":\"mutation createDataEntries($sessionToken: String!, $siteIds:String!, $params: [masterDataInput!]){createDataEntries(sessionToken: $sessionToken,siteIds: $siteIds, params: $params){dataId status statusMessage}}\",\"variables\":{\"sessionToken\":" + sessionToken + ",\"siteIds\":" + siteIds + ",\"params\":" + JSON.stringify(paramsArray) + "}}"
            }
            $.ajax(settings).done(function (response) {

                searchMasterData(index, cssSearchClass, csslabelvalue)
                $(".dynamicelementsModalClose").trigger('click');
                $(".dynamicContent").html('');
                setTimeout(function () {
                    if (response['data']['createDataEntries'].statusMessage == "Success") {
                        if ($("#types").val() == 1) {
                            prepopulateData(index, response['data']['createDataEntries'].dataId, csslabelvalue, cssSearchClass)
                        }
                        $("#popalertpopup_" + index).modal('show')
                        setTimeout(function () { $('#popalertpopup_' + index).modal('hide'); }, 4000);
                        $(".modal-backdrop.in").hide();
                        requiredArray = [];
                    } else {
                        $("#popalertpopup1_" + index).modal('show')
                        setTimeout(function () { $('#popalertpopup1_' + index).modal('hide'); }, 4000);
                        $(".modal-backdrop.in").hide();
                    }
                }, 1000);
            }).fail(function (data) {

            })

        }
    }
}
// session unique in multiple tabs checking
/**
 * appendBaseUrl
 * Extract base url for ajax call
 * @param String
 * @return String
 */
 function appendBaseUrl(serverBaseUrl)
 {
     var base_urlnew = serverBaseUrl.replace("%3A%2F%2F", "://");
     base_urlnew = base_urlnew.replace("%2F", "/");
     base_urlnew = base_urlnew.replace("%2F", "/");
     base_urlnew = base_urlnew.replace("machform/Upload/undefined/", "");
     base_urlnew = base_urlnew.replace("%253A%252F%252F", "://");
     base_urlnew = base_urlnew.replace("%252F", "/");
     base_urlnew = base_urlnew.replace("%252F", "/");
     base_urlnew = base_urlnew.replace("%252F", "/");
     return base_urlnew;
 }
 var errorCodesDisplay = [1054];
 // exception error code handling to message
 /**
 * errorCodeHandling
 * Extract base url for ajax call
 * @param Integer
 * @return Object
 */
function errorCodeHandling(code){
    var errorCodeMessage = {
        1054:{"message":"This form has errors. Please contact your manager. This Form error can be fixed from Manage Form section by using Fix Form Errors action.", "popTitle": "Error", "iconType": "error"}
    };
    return errorCodeMessage[code];
}
