$(document).ready(function () {
    (function (document, window, index)
    {
        var inputs = document.querySelectorAll('.inputfile');
        Array.prototype.forEach.call(inputs, function (input)
        {
            var label = input.nextElementSibling,
            labelVal = label.innerHTML;

            input.addEventListener('change', function (e)
            {
                var fileName = '';
                if (this.files && this.files.length > 1)
                    fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
                else
                    fileName = e.target.value.split('\\').pop();

                if (fileName)
                    label.querySelector('span').innerHTML = fileName;
                else
                    label.innerHTML = labelVal;
            });

            // Firefox bug fix
            input.addEventListener('focus', function () {
                input.classList.add('has-focus');
            });
            input.addEventListener('blur', function () {
                input.classList.remove('has-focus');
            });
        });


        // To open give_feedback and request_feedback modal by default on page load
        const url = new URL(window.location.href);
        const intent_name = url.searchParams.get("fromChatBot");
        if(intent_name === 'give_feedback') {
            $(".feedback").trigger("click");
        } else if(intent_name === 'request_feedback') {
            setTimeout(() => {
                $(".request-feedback").trigger("click");
            }, 800);
        }
    }(document, window, 0));
});

/**
 * Sends message to chat-bot
 * @param {Object} message Message to broadcast via localStorage to ChatBot
 * @param {string} message.intent Intent name received from URL
 * @param {1|0} message.status Status 1 or 0, 1- success, 0- failure
 * @param {string} message.tab_id Tab Id received from URL
 */
function message_broadcast(message) {
    localStorage.setItem('dbox_tab_msg', JSON.stringify(message));
    localStorage.removeItem('dbox_tab_msg');
}

$(document).on("click", ".reply-message-module #message_submit_btn", function (e) {
    e.preventDefault();
        //console.log("sandip");
    var $this = $(this);
    var formData = $(this).closest("form");
    $.ajax({
        type: "POST",
        data: formData.serialize(),
        dataType: "json",
        url: formData.attr("action"),
        beforeSend: function () {
                //e.target.value = "Posting...";
            $this.attr("disabled", "disabled");
        },
        success: function (data) {
            if (data.status == "success") {
                $("#" + data.message).append(data.update);
                var msg_id = data.message.replace("message_replies_", "");
                $("#thread_reply_" + msg_id).html("");
                $("#thread_reply_" + msg_id).html(data.reply);

            } else {
                var errorContent = "<div class=\'alert-message warning fade in\' data-alert=\'alert\'><button type=\'button\' class=\'close\' data-dismiss=\'alert\'>&times;</button><p>" + data.error + "</p></div>";
                $("#" + data.message).html(errorContent);
                e.target.value = "Share";
            }
            mentionsAutoComplete();
            trimMessageText();
            Shadowbox.setup("a.shadowbox");
            $this.removeAttr("disabled", "disabled");
        },
    });
});

$(document).on("click", ".feedback", function (e) {
    e.preventDefault();
    var $this = $(this);
    var bus = $this.attr("id");
    $.ajax({
        type: "POST",
        data: {resource: bus, mode: "open"},
        dataType: "json",
        url: "/feedback/give",
        success: function (data) {
            if (data.status == "success") {
                $("#edit_comp_bus_modal_output").html("");
                $("#edit_comp_bus_modal_output").html(data.update);
                var myModal = new bootstrap.Modal(document.getElementById('edit_comp_bus_modal'), {
                    backdrop: "static",
                    show: true,
                    keyboard: true
                })
                myModal.toggle();
            }
        },
    });
});
$(document).on("click", "#give_feedback_global", function (e) {
    e.preventDefault();
    if($('#goals_check').is(":checked") && $('.goals_options input:checked').length == 0 || $('#comp_check').is(":checked") && $('.competencies_options input:checked').length == 0 || $('#skills_check').is(":checked") && $('.skills_options input:checked').length == 0){
       showNotification({message:"You need to select at least one check box", type:"error"})
       return false;
   } else {
    var $this = $(this);
    var formData = $(this).closest("form");
    $.ajax({
        type: "POST",
        data: formData.serialize(),
        dataType: "json",
        url: formData.attr("action"),
        success: function (data) {
            var url = new URL(window.location.href);
            var intent_name = url.searchParams.get("fromChatBot");
            const tab_id = url.searchParams.get("tab_id");
            if (data.status === "success") {
                if(intent_name === "give_feedback"){
                    message_broadcast({"intent":intent_name,"status":1, "tab_id": tab_id});
                }
                $("#edit_comp_bus_modal").modal("hide").remove();
                showNotification({
                  message: data.message,
                  type: "success",
                  autoClose: true,
                  duration: 5
              });
                $("body").removeClass("modal-open");
                $(".modal-backdrop").remove();
                window.location.reload();
            } else {
                if(intent_name === "give_feedback"){
                    message_broadcast({"intent":intent_name,"status":0, "tab_id": tab_id});
                }
                $(".feedback_req #input-error").html("").html(data.error).removeClass("hidden");
                showNotification({
                  message: data.message,
                  type: "error",
                  autoClose: true,
                  duration: 5
              });
            }
        },
    });
}
});

// $(document).on("focus", ".set-table-input-width input", function (e) {
//     $(this).css("width", "100px");
// });
// $(document).on("blur", ".set-table-input-width input", function (e) {
//     $(this).css("width", "40px");
// });

// code for employee search USER ID
//adding tag input function
$.fn.createEmpTagInput = function (outputID, company_filter, grp_cmp_id, token_options = {}, include_all_status = false, exculde_extra_filters = false, exclude_position = false, separator = false){
    company_filter = company_filter || false;
    include_all_status = include_all_status || false;
    separator = separator || ",";
    grp_cmp_id = grp_cmp_id || null;
    $myParent = $(this).parent();
    var $meItSelf = $(this);
    var value_store =[];
    var prevLable, prevId
    if(typeof $('#'+outputID).val() != "undefined"){
        $('#'+outputID).val($('#'+outputID).val().replace(/\|+$/,''))
    }
    if($(this).val()!=="")
        if(typeof $(this).val() !="undefined"){
            prevLable = $(this).val().split(separator);
        }
        if($('#'+outputID).val()!=="")
            if(typeof $('#'+outputID).val() != "undefined"){
                prevId = $('#'+outputID).val().replace(/\|+$/,'').split(separator);
            }
            var prevObject={}, prevObjectArr=[]
            if(typeof prevLable !="undefined"){
                for(var indx=0; indx<prevLable.length; indx++){
                    prevObject = {
                        "label" : prevLable[indx],
                        "value" : prevLable[indx],
                        "id" : [prevId[indx]]
                    }
                    prevObjectArr.push(prevObject)
                }
            }
            $(this).on('tokenfield:edittoken',function (e) {
                e.preventDefault();
            })
            .on('tokenfield:removedtoken',function (e) {
                value_store = []
                $(this).tokenfield('getTokens').forEach(function(item){
                    value_store.push(item.id)
                })
                $('#'+outputID).val(value_store.join(separator))
                $(this).closest('div').children('input.value-store').val(value_store.join(separator))
                if($(this).val()=="")
                    $(this).data('bs.tokenfield').$input.attr("placeholder", "Start typing name");
            }).tokenfield(token_options);
            $(this).tokenfield('setTokens',prevObjectArr);

            $(this).parent().css({
                "height": "auto",
                "min-height": "40px"
            });
            $myParent.find("input.token-input").css({
                "margin-left": "-12px",
                "padding-left": "12.55px",
                "width" : "100%"                                        
            });
            $myParent.on("keydown", "input.token-input", function (event) {
                if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active) { 
                    event.preventDefault();
                }
                $(this).width($(this).closest("div").parent().width());
                $(this).autocomplete({
                    source: function (request, response) {
                        var searchTerm = this.term;
                        var ids = {};
                        if(company_filter){
                            var grpcompsend = grp_cmp_id;
                            var url = "/dashboard/GetEmployeesUserIdAdmin";
                            $.getJSON(url, {
                                term: extractLast(searchTerm),
                                grpcompsend:grpcompsend,
                                is_hrdocs: include_all_status ? 1 : 0
                            }, response);
                        }
                        else{
                            var url = "/dashboard/GetEmployeesUserId";
                            const status = include_all_status ? [1,2,3] : [1];
                            if($("#request_type").val() === 'onboarding_task') {
                               status.push(2);
                            }
                            if (exculde_extra_filters){
                                payload = {
                                    term: extractLast(searchTerm),
                                    status: JSON.stringify(status)
                                }
                            }
                            else {    
                                payload = {
                                    term: extractLast(searchTerm),
                                    grp_cmp: $("#grp_comp").val(),
                                    business_unit: $("#business_unit").val(),
                                    department: $("#dept").val(),
                                    location: $("#location").val(),
                                    job_level: $("#job_level").val(),
                                    emp_type: $("#emp_type").val(),
                                    status: JSON.stringify(status)
                                }
                                if (exclude_position) {
                                    payload.ignorePositionSearch = 1;
                                }
                            }
                            
                            $.getJSON(url, payload, function(data) {
                                const existingTokens = $meItSelf.tokenfield("getTokens");
                                if(existingTokens.length){
                                    const result = data.filter(element => !existingTokens.some(token => token.id[0] === element.id[0]));
                                    response(result);
                                } else {
                                    response(data);
                                }
                               });
                       }
                   },
                   search: function () {
                    var searchTerm = $(this).val();
                    var term = extractLast(searchTerm);
                    if (term.length < 2) {
                        return false;
                    }
                },
                focus: function () {
                    return false;
                },
                select: function (event, ui) {
                    if(!$('#'+outputID).val()==""){
                        value_store = $('#'+outputID).val().split(separator);
                    } else if ($('#'+outputID).val()=="") {
                        value_store = [];
                    }
                    if(company_filter){
                        value_store.push(ui.item.id.split("_").pop())
                    }
                    else{
                        value_store.push(ui.item.id[0])
                    }
                    $('#'+outputID).val(value_store.join(separator))
                    $(this).width($(this).closest("div").parent().width()).attr("placeholder", "");
                },
                change: function (e, ui) {
                }
            }).data("ui-autocomplete")._renderMenu = function( ul, items ) {
                    var that = this,
                    currentCategory = "";
                    $.each( items, function( index, item ) {
                        var li;
                        if ( item.category != currentCategory ) {
                            ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
                            currentCategory = item.category;
                        }
                        li = that._renderItemData( ul, item );
                        if ( item.category ) {
                            li.attr( "aria-label", item.category + " : " + item.label );
                        }
                    });
                    $( ul ).addClass( "global-search-autocomplete" );
                };
                $(this).data("ui-autocomplete")._renderItem = function( ul, item ) {
                    var href = item.href ? item.href : 'javascript:void(0)';
                    return $( "<li>" )
                    .append( "<div class='search-item'><a href='"+href+"'>" + item.label + "</a></div>" )
                    .appendTo( ul );  
                };
        }); // eof autocomplete 
        };

        $.fn.createEmpGrpCompTagInput = function(outputID,grp_comp_sel,replace_str){
            $myParent = $(this).parent();
            $meItSelf = $(this);
            var value_store =[];
            var prevLable, prevId
            if(typeof $('#'+outputID).val() != "undefined"){
                $('#'+outputID).val($('#'+outputID).val().replace(/,+$/,''))
            }
            if($(this).val()!=="")
                if(typeof $(this).val() !="undefined"){
                    prevLable = $(this).val().split(",");
                }
                if($('#'+outputID).val()!=="")
                    if(typeof $('#'+outputID).val() != "undefined"){
                        prevId = $('#'+outputID).val().replace(/,+$/,'').split(",");
                    }
                    var prevObject={}, prevObjectArr=[]
                    if(typeof prevLable !="undefined"){
                        for(var indx=0; indx<prevLable.length; indx++){
                            prevObject = {
                                "label" : prevLable[indx],
                                "value" : prevLable[indx],
                                "id" : [prevId[indx]]
                            }
                            prevObjectArr.push(prevObject)
                        }
                    }

                    $(this)
                    .on('tokenfield:edittoken',function (e) {
                        e.preventDefault();
                    })
                    .on('tokenfield:removedtoken',function (e) {
                        value_store = []
                        $(this).tokenfield('getTokens').forEach(function(item){
                            var uid = item.id;
                            if(typeof uid=="string")
                                value_store.push(uid.replace("NAME_",""))
                            else
                                value_store.push(uid)
                        })
                        $('#'+outputID).val(value_store.join())
                        $(this).closest('div').children('input.value-store').val(value_store.join())
                        if($(this).val()=="")
                            $(this).data('bs.tokenfield').$input.attr("placeholder", "Start typing name");
                    })
                    .tokenfield();

                    $(this).tokenfield('setTokens',prevObjectArr);

                    $(this).parent().css({
                        "height": "auto",
                        "min-height": "40px"
                    });
                    $myParent.find("input.token-input").css({
                        "margin-left": "-12px",
                        "padding-left": "12.55px",
                        "width" : "100%"
                    });

                    $myParent
                    .on("keydown", "input.token-input", function (event) {
                        if (event.keyCode === $.ui.keyCode.TAB &&
                            $(this).autocomplete("instance").menu.active) { 
                            event.preventDefault();
                    }
                    $(this).width($(this).closest("div").parent().width());
                    var grp_comp_id = $('#'+grp_comp_sel).val().replace(replace_str,"");
                    $(this).autocomplete({
                        source: function (request, response) {
                            var searchTerm = this.term;
                            var ids = {};
                            var url = "/dashboard/GetEmployeesUserIdAdmin";

                            $.getJSON(url, {
                                term: searchTerm,
                                grpcompsend: (grp_comp_id == "main" ? "" : grp_comp_id),
                                type: 'others',
                                only_names: true
                            }, response);
                        },
                        search: function () {
                            var searchTerm = $(this).val();
                            var term = extractLast(searchTerm);
                            if (term.length < 2) {
                                return false;
                            }
                        },
                        focus: function () {
        // prevent value inserted on focus
                            return false;
                        },
                        select: function (event, ui) {
                            if($('#'+outputID).val()!=="")
                                value_store = $('#'+outputID).val().split(",");
                            else
                                value_store = []
                            var uid = ui.item.id;        
                            value_store.push(uid.replace("NAME_",""))
                            $('#'+outputID).val(value_store.join())
                            $(this).width($(this).closest("div").parent().width()).attr("placeholder", "");

            // return false;
                        },
                        change: function (e, ui) {
                        }
                    });
    }); // eof autocomplete 
                };

// ACTIVE INACTIVE ALL EMPLOYEES SEARCH
                $.fn.createEmpTagInputInactive = function(outputID){
                    $myParent = $(this).parent();
                    $meItSelf = $(this);
                    var value_store =[];
                    var prevLable, prevId
                    if(typeof $('#'+outputID).val() != "undefined"){
                        $('#'+outputID).val($('#'+outputID).val().replace(/,+$/,''))
                    }
                    if($(this).val()!=="")
                        if(typeof $(this).val() !="undefined"){
                            prevLable = $(this).val().split(",");
                        }
                        if($('#'+outputID).val()!=="")
                            if(typeof $('#'+outputID).val() != "undefined"){
                                prevId = $('#'+outputID).val().replace(/,+$/,'').split(",");
                            }
                            var prevObject={}, prevObjectArr=[]
                            if(typeof prevLable !="undefined"){
                                for(var indx=0; indx<prevLable.length; indx++){
                                    prevObject = {
                                        "label" : prevLable[indx],
                                        "value" : prevLable[indx],
                                        "id" : [prevId[indx]]
                                    }
                                    prevObjectArr.push(prevObject)
                                }
                            }
                            $(this)
                            .on('tokenfield:edittoken',function (e) {
                              e.preventDefault();
                          })
                            .on('tokenfield:removedtoken',function (e) {
            // console.log("Selected Value : ",e);
            // console.log("Selected token : ",e.attrs.id[0]);
            // console.log("get tokenlist",$(this).tokenfield('getTokens'))
            // value_store = removeFromArray(value_store,e.attrs.id[0])
                                value_store = []
            // value_storeR = $(this).tokenfield('getTokens')[0].id[0]
                                $(this).tokenfield('getTokens').forEach(function(item){
                                    value_store.push(item.id[0])
                                })
            // console.log(value_store)
                                $('#'+outputID).val(value_store.join())
                                $(this).closest('div').children('input.value-store').val(value_store.join())
                                if($(this).val()=="")
                                  $(this).data('bs.tokenfield').$input.attr("placeholder", "Start typing name");
                          })
                            .tokenfield();
                            $(this).tokenfield('setTokens',prevObjectArr);

                            $(this).parent().css({
                                "height": "auto",
                                "min-height": "40px"
                            });
                            $myParent.find("input.token-input").css({
                                                // "height" : "36px",
                                "margin-left": "-12px",
                                "padding-left": "12.55px",
                                "width" : "100%"
                            });
                            $myParent
                            .on("keydown", "input.token-input", function (event) {
                                if (event.keyCode === $.ui.keyCode.TAB &&
                                    $(this).autocomplete("instance").menu.active) { 
                                    event.preventDefault();
                            }
                            $(this).width($(this).closest("div").parent().width());
                            $(this).autocomplete({
                                source: function (request, response) {
                                    var searchTerm = this.term;
                                    var ids = {};
                                    var url = "/dashboard/GetEmployeesUserIdWithInactive";
                                    $.getJSON(url, {
                                        term: extractLast(searchTerm)
                                    }, response);
                                },
                                search: function () {
                                    var searchTerm = $(this).val();
                                    var term = extractLast(searchTerm);
                                    if (term.length < 2) {
                                        return false;
                                    }
                                },
                                focus: function () {
                            // prevent value inserted on focus
                                    return false;
                                },
                                select: function (event, ui) {
                                    if($('#'+outputID).val()!=="")
                                        value_store = $('#'+outputID).val().split(",");
                        // console.log('valu-store',value_store)
                                    value_store.push(ui.item.id[0])
                        // console.log(value_store.join())
                                    $('#'+outputID).val(value_store.join()).trigger('change');
                                    $(this).width($(this).closest("div").parent().width()).attr("placeholder", "");

                        // return false;
                                },
                    // appendTo: $(this).width($(this).closest("div").parent(),
                                change: function (e, ui) {
                                }
                            });
            }); // eof autocomplete 
                        };
// ACTIVE INACTIVE ALL EMPLOYEES SEARCH

//EMPLOYEES SEARCH BASED ON FILTERS
                        $.fn.createFiltersEmpTagInput = function(outputID,status){
                            if(!status){
                                status = [];
                            }
                            $myParent = $(this).parent();
                            $meItSelf = $(this);
                            var value_store =[];
                            var prevLable, prevId
                            if(typeof $('#'+outputID).val() != "undefined"){
                                $('#'+outputID).val($('#'+outputID).val().replace(/,+$/,''))
                            }
                            if($(this).val()!=="") {
                                if(typeof $(this).val() !="undefined"){
                                    prevLable = $(this).val().split(",");
                                }
                            }
                            if($('#'+outputID).val()!==""){
                                if(typeof $('#'+outputID).val() != "undefined"){
                                    prevId = $('#'+outputID).val().replace(/,+$/,'').split(",");
                                }
                            }
                            var prevObject={}, prevObjectArr=[]
                            if(typeof prevLable !="undefined"){
                                for(var indx=0; indx<prevLable.length; indx++){
                                    prevObject = {
                                        "label" : prevLable[indx],
                                        "value" : prevLable[indx],
                                        "id" : [prevId[indx]]
                                    }
                                    prevObjectArr.push(prevObject)
                                }
                            }
                            $(this).on('tokenfield:edittoken',function (e) {
                                e.preventDefault();
                            })
                            .on('tokenfield:removedtoken',function (e) {
                                value_store = []
                                $(this).tokenfield('getTokens').forEach(function(item){
                                    value_store.push(item.id[0])
                                })
                                $('#'+outputID).val(value_store.join())
                                $(this).closest('div').children('input.value-store').val(value_store.join())
                                if($(this).val()==""){
                                    $(this).data('bs.tokenfield').$input.attr("placeholder", "Start typing name");
                                }
                            }).tokenfield();
                            $(this).tokenfield('setTokens',prevObjectArr);
                            $(this).parent().css({
                                "height": "auto",
                                "min-height": "40px"
                            });
                            $myParent.find("input.token-input").css({
                                "margin-left": "-12px",
                                "padding-left": "12.55px",
                                "width" : "100%"
                            });
                            $myParent.on("keydown", "input.token-input", function (event) {
                                if (event.keyCode === $.ui.keyCode.TAB &&
                                    $(this).autocomplete("instance").menu.active) { 
                                    event.preventDefault();
                            }
                            $(this).width($(this).closest("div").parent().width());
                            $(this).autocomplete({
                                source: function (request, response) {
                                    var searchTerm = this.term;
                                    var ids = {};
                                    var url = "/dashboard/GetFilteredEmployeesUserId";
                                    $.getJSON(url, {
                                        term: extractLast(searchTerm),
                                        status: status
                                    }, response);
                                },
                                search: function () {
                                    var searchTerm = $(this).val();
                                    var term = extractLast(searchTerm);
                                    if (term.length < 2) {
                                        return false;
                                    }
                                },
                                focus: function () {
                // prevent value inserted on focus
                                    return false;
                                },
                                select: function (event, ui) {
                                    if($('#'+outputID).val()!=="")
                                        value_store = $('#'+outputID).val().split(",");
                                    value_store.push(ui.item.id[0])
                                    $('#'+outputID).val(value_store.join())
                                    $(this).width($(this).closest("div").parent().width()).attr("placeholder", "");
                                },
                                change: function (e, ui) {
                                }
                            });
    }); // eof autocomplete 
                        };
//EMPLOYEES SEARCH BASED ON FILTERS

                        function darwinboxAJAXUploader(max_file_upload_size, msg_id) {
                            var file_elem, file_list_elem;
                            if (msg_id == null) {
                                file_elem = document.getElementById('file-uploader-top');
                                file_list_elem = '#file-list-top';
                            } else {
                                file_elem = document.getElementById('file-uploader-' + msg_id);
                                file_list_elem = '#file-list-' + msg_id;
                            }

                            var counter = 0;
                            var max_file_size = max_file_upload_size;
                            var uploader = new qq.FileUploader({
                                element: file_elem,
                                action: '/document/doupload',
                                debug: false,
                                maxConnections: 1,
                                onSubmit: function (id, filename, uploadname) {
                                    var file_elem = '<input id="filename_' + id + '" type="hidden" name="Messages[files][' + id + '][filename]" value="' + filename + '" />';
                                    $(file_list_elem).append(
                                     "<li class='fileicon-listelement fileicon-listelement-old' id='file-upload-elem-" + id + "'>"
                                     + '<span class="file label label-info" style="font-size:11px;">Queued...</span>'
                                     + file_elem
                                     + '<a title="Remove File" href="#" class="marginLeft-5 fileicon-close" style="color:#FF0000; font-weight:bold; font-size:16px;"><i class="fa fa-remove"></i></a>'
                                     + "</li>"
                                     );
                                    $("#message_submit_btn").addClass('disabled').attr('disabled', 'disabled');
                                },
                                onProgress: function (id, filename, loaded, total) {
                                    $("li#file-upload-elem-" + id + " span.file").html("Uploading... " + parseInt((loaded / total) * 100) + "%");
                                },
                                onComplete: function (id, filename, result, uploadname) {
                                    if (typeof result.error === "undefined") {
                                        var filedata1 = '<input type="hidden" name="Messages[files][' + id + '][size]" value="' + result.size + '" />';
                                        var filedata2 = '<input type="hidden" name="Messages[files][' + id + '][mime]" value="' + result.mime + '" />';
                                        var filedata3 = '<input type="hidden" name="Messages[files][' + id + '][uploadname]" value="' + result.uploadname + '" />';
                                        var filedata4 = '<input type="hidden" name="Messages[files][' + id + '][bucket]" value="' + result.bucket + '" />';
                                        var filedata5 = '<input type="hidden" name="Messages[files][' + id + '][key]" value="' + result.key + '" />';
                                        $('#file-upload-elem-' + id).append(filedata1).append(filedata2).append(filedata3).append(filedata4).append(filedata5);

                /* Replace with new Filename - Multiple versions of the file is stored */
                                        $("#filename_" + id).val(result.filename);

                                        $("li#file-upload-elem-" + id + " span.file").html(result.uploadname);
                                        $("#message_submit_btn").removeClass('disabled').removeAttr('disabled');
                                    } else {
                                        $("#file-upload-elem-" + id).remove();
                                    }
                                },
                                showMessage: function (message) {
                                    showNotification({
                                        type: "error",
                                        autoClose: true,
                                        duration: 5,
                                        message: 'Oops an error occured while uploading the file: ' + message
                                    });
                                }
                            });
                        };

                        function formatSize(bytes) {
                            var i = -1;
                            do {
                                bytes = bytes / 1024;
                                i++;
                            } while (bytes > 99);

                            return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];
                        }

                        function formatName(name) {
                            if (name.length > 18) {
                                name = name.slice(0, 10) + '...' + name.slice(-8);
                            }
                            return name;
                        }

                        function getExt(file) {
                            var ext = file.substr((file.lastIndexOf('.') + 1));
                            return ext;
                        }

                        function split(val) {
    return val.split(/@\s*/);
                        }

                        function extractLast(term) {
                            return split(term).pop();
                        }

                        function mentionsAutoComplete() {
                            $(".message-box-text")
                            .bind("keyup", function (event) {
                                if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
                                    event.preventDefault();
                                }
                            })
                            .autocomplete({
                                minLength: 0,
                                matchCase: 0,
                                source: function (request, response) {
                                    var term = request.term,
                                    results = [];
                                    if (term.indexOf("@") >= 0) {
                                        term = extractLast(request.term);
                                        if (term.length > 0) {
                                            $.ajax({
                                                method: "POST",
                                                url: "/dashboard/omniSuggestion",
                                                dataType: "json",
                                                data: {term: term},
                                                success: function(data) {
                                                    response( $.map( data, function( term ) {
                                                        var object = new Object();
                                                        object.value = term.value;
                                                        object.email = (term.email) ? term.email.replace("@", ".") : term.email;
                                                        object.category = term.category;
                                                        return object;
                                                    }));
                                                }
                                            })

                                        } else {
                                            results = ['Type in the Person you want to mention...'];
                                        }
                                    }
                                    response(results);
                                },
                                focus: function () {
                                    return false;
                                },
                                select: function (event, ui) {
                                    var terms = split(this.value);
                                    var clean = this.value;
                                    this.value = clean.substring(clean,clean.lastIndexOf("@" + terms[terms.length - 1])) + "@" + ui.item.email;
                                    return false;
                                }
                            });
                        }

                        var globalTabs;
                        function globalMentions() {
                            $('textarea.mention').mentionsInput({
                                onDataRequest: function (mode, query, callback) {
                                    var data = globalTabs;
                                    data = _.filter(data, function (item) {
                                        return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1
                                    });

                                    callback.call(this, data);
                                },
                                minChars: 1,
                                elastic: false
                            });
                        }

                        function orgChartGenerate() {
                            var $imgWrap = $("#imageWrapper"), heightPercent, widthPercent;
                            var divHeight, divWidth, wrapHeight = $imgWrap.height(),
                            wrapWidth = $imgWrap.width();

    /*$("#org").orgChart({
     levels: -1,
     stack: false,
     nodeText: function($node) {
     var nodeData = $node.textChildren().split(":");
     var nodeText = nodeData[0];
     var nodeID = nodeData[1];
     var nodeCaption = nodeData[2];
     if(nodeCaption === undefined) {
     var u = "<div class='node-container'>" + "<h6 class='item-name'>" + nodeText + "</h6></div>";
     } else {
     var u = "<div class='node-container'>" + "<h6 class='item-name'>" + nodeText + "</h6>" + "<span class='item-caption'>"+nodeCaption+"</span></div>";
     }
     if (nodeID != null) {
     u += "<a id='" + nodeID + "' class='edit' style='display: none;'>Change Manager</a>";
     }
     return u;
     }
 }, $("#orgContainer"));*/

                            $("#org").jOrgChart({
                                chartElement: "#orgContainer"
                            });

                            $copy = $("#clone").html($imgWrap.html());
                            divHeight = $copy.height();
                            divWidth = $copy.width();
                            $copy.remove();
                            heightPercent = (divHeight - wrapHeight) / wrapHeight;
                            widthPercent = (divWidth - wrapWidth) / wrapWidth;

                            $imgWrap.mousemove(function (e) {
                                e.preventDefault();
                                var x = e.pageX - this.offsetLeft;
                                var y = e.pageY - this.offsetTop;
                                y = y * heightPercent;
                                x = x * widthPercent;
                                $(this).stop().animate({
                                    scrollTop: y,
                                    scrollLeft: x
                                }, 1, "linear");
                            });

                            $("div.node").hover(
                                function (e) {
                                    e.preventDefault();
                                    $(this).find("a.edit").show();
                                },
                                function (e) {
                                    e.preventDefault();
                                    $(this).find("a.edit").hide();
                                }
                                );
                        }

                        function getElementsByClass(searchClass, node, tag) {
                            var classElements = new Array();
                            if (node == null) {
                                node = document;
                            }
                            if (tag == null) {
                                tag = '*';
                            }
                            var els = node.getElementsByTagName(tag);
                            var elsLen = els.length;
                            var pattern = new RegExp('(^|\\\\s)' + searchClass + '(\\\\s|$)');
                            for (i = 0, j = 0; i < elsLen; i++) {
                                if (pattern.test(els[i].className)) {
                                    classElements[j] = els[i];
                                    j++;
                                }
                            }
                            return classElements;
                        }

                        function linkify(inputText) {
                            var replaceText, replacePattern1, replacePattern2, replacePattern3;

    //URLs starting with http://, https://, or ftp://
                            replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
                            replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
                            replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
                            replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

    //Change email addresses to mailto:: links.
                            replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
                            replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

                            return replacedText
                        }

                        function trimMessageText() {
                            $(".message-body .message-text").expander({
                                slicePoint: 150,
                                expandText: "Read more",
                                userCollapseText: "Read less"
                            });
                            $(".message-reply-body .message_reply_body_container").expander({
                                slicePoint: 150,
                                expandText: "Read more",
                                userCollapseText: "Read less"
                            });
                            $(".message-attachment blockquote").expander({
                                slicePoint: 150,
                                expandText: "Read more",
                                userCollapseText: "Read less"
                            });
                        }
                        function getCompetencyScaleAjax(optVal) {
                            $("#scale_lenght_table").empty();
                            $("#scale_lenght_table").html("<thead><tr class='text-uppercase tr-bg1'></tr></thead>");
                            var scaleIdLen = optVal.split("_");
                            var scaleLen = parseInt(scaleIdLen[1]);
                            var scaleId = scaleIdLen[0];
                            var scaleAjaxUrl = '/settings/getScaleMarker';
                            $.ajax({
                                type: "POST",
                                data: {"scale_id": scaleId},
                                dataType: "json",
                                url: scaleAjaxUrl,
                                success: function (data) {

                                    var len_a = data.aaData.length;
                                    var tbl_html = '';
                                    for (var i = -1; i <= len_a; i++) {
                                        if (i === -1) {
                                            tbl_html = '<td class="text-center">' + "Proficiency Indicators" + '</td>';
                                        } else if (i === len_a) {
                                            tbl_html = '<td class="text-center">' + "action" + '</td>';
                                        } else {
                                            tbl_html = '<td class="text-center">' + data.aaData[i].scale_marker + '</td>';
                                        }
                                        $("#scale_lenght_table tr:first").append(tbl_html);

                                    }
                                    competencyAppendRow('scale_lenght_table');
                                }
                            });
                        }

                        function getSkillScaleAjax(optVal) {
                            $("#scale_lenght_table").empty();
                            $("#scale_lenght_table").html("<tr></tr>");
                            var scaleId = optVal;
                            var scaleAjaxUrl = '/settings/getScaleMarker';
                            $.ajax({
                                type: "POST",
                                data: {"scale_id": scaleId},
                                dataType: "json",
                                url: scaleAjaxUrl,
                                success: function (data) {

                                    var len_a = data.aaData.length;
                                    var tbl_html = '';
                                    for (var i = -1; i <= len_a; i++) {
                                        if (i === -1) {
                                            tbl_html = '<td>' + "Proficiency Indicators" + '</td>';
                                        } else if (i === len_a) {
                                            tbl_html = '<td>' + "action" + '</td>';
                                        } else {
                                            tbl_html = '<td>' + data.aaData[i].scale_marker + '</td>';
                                        }
                                        $("#scale_lenght_table tr:first").append(tbl_html);

                                    }
                                    competencyAppendRow('scale_lenght_table');
                                }
                            });
                        }

                        function competencyAppendRow(id) {
                            var l = $("#" + id + " tr:first td").length
                            var counter = 0;
                            $("#" + id).each(function () {
                                var tbody = $(this).find("tbody");
                                if (!tbody.length) {
                                    tbody = $("<tbody></tbody>").appendTo($(this));
                                }
                                var tds = '<tr>';
                                jQuery.each($('tr:last td', this), function () {
                                    if (counter === 0) {
                                        tds += '<td class="text-center">' + '<textarea name=indicator_name[] value="indicator name" style="resize:none;width: 160px;">indicator name</textarea>' + '</td>';
                                    } else if (counter === l - 1) {
                                        tds += '<td class="text-center">' + '<div><a href="#" class="insert-more"> +Add  </a></div><div><a href="#" class="delete-row circle-btn close-text delete-bus"> <i class="fa fa-trash"></i> </a></div>' + '</td>';
                                    } else {
                                        tds += '<td class="text-center">' + '<textarea name=indicator_scale_' + counter + '[] value="" style="resize:none;width: 160px;"></textarea>' + '</td>';
                                    }
                                    counter++;
                                });

                                tds += '</tr>';
                                if ($('tbody', this).length > 0) {
                                    $('tbody', this).append(tds);
                                } else {
                                    $(this).append(tds);
                                }
                            });
                            counter.delete;
                        }
//logo-size-fix
// $(document).ready(function(){
//     $logoImg = $('.logoheader>a>img, .main-navigation1 .logo1 img');
//     $logoImg.each(function(){
//         // $(this).load(function(){
//             var logoHeight = $(this).height();
//             if(logoHeight<65 && logoHeight>16){
//               $(this).css({
//                 "margin-top": (70-logoHeight)/2+"px",
//                 "margin-left": "10px",
//                 "height": logoHeight+"px",
//                 "width": "auto",
//             });
//           }
//           else{
//               $(this).css({
//                 "margin-top": "8px",
//                 "margin-left": "10px",
//                 "height": "65px",
//                 "width": "auto",   
//             });    
//           }
//       // });
//   });
// });
                        jQuery(document).ready(function() {
                            function close_accordion_section() {
                                jQuery('.accordion .accordion-section-title').removeClass('active').find("i.indicator").removeClass('fa-minus').addClass('fa-plus');
                                jQuery('.accordion .accordion-section-content').slideUp(300).removeClass('open');
                            }

                            jQuery('.accordion-section-title').click(function(e) {
        // Grab current anchor value
                                var currentAttrValue = jQuery(this).attr('href');

                                if(jQuery(this).is('.active')) {
                                    close_accordion_section();
                                }else {
                                    close_accordion_section();

            // Add active class to section title
                                    jQuery(this).addClass('active');
            // Open up the hidden content panel
                                    jQuery('.accordion ' + currentAttrValue).slideDown(300).addClass('open');
                                    $(this).find("i.indicator").removeClass('fa-plus').addClass('fa-minus');    
                                }
                                e.preventDefault();
                            });
                        });
                        $(function(){
                          $(".org-name").each(function(){
                            $(this).append('<span class="tooltiptext">'+$(this).html()+'</span>');
                        });
                      });
                        $(function(){
                          $("body").on({
                            click : function(){
                              $(this).closest(".rate-bar-pill").find("a").removeClass("br-selected");
              $(this).addClass("br-selected");//.prevAll().addClass("br-selected");
              $(this).closest(".rate-bar-pill").find(".bar-pill-txt").html($(this).attr("data-text"));
              $(this).closest(".rate-bar-pill").find(".bar-pill-selected-value").val($(this).attr("data-value"));
          },
          mouseover : function(){
                $(this).addClass("br-active");//.prevAll().addClass("br-active");
                $(this).closest(".rate-bar-pill").find(".bar-pill-txt").html($(this).attr("data-text"));
            },
            mouseout : function(){
                $(this).removeClass("br-active").prevAll().removeClass("br-active");
                $(this).closest(".rate-bar-pill").find(".bar-pill-txt").html("");
                $(this).closest(".rate-bar-pill").find(".bar-pill-txt").html($(this).closest(".rate-bar-pill").find(".br-selected").last().attr("data-text"));
            }
        },".rate-bar-pill a");
                      });
/*$(function(){
    $('.br-widget .br-selected').prevAll("a").css({"background-color": "#50E3C2","color": "white"});
});*/
                        $(function(){
                            $(".stepwizard-row1").each(function(){
                              var count = 0;
                              var flag = 0;
                              var html = "";
                              var final_html="";
                              $(this).children().each(function(){
                                count++;
                                if(count >4){
                                  flag = 1;
                                  final_html += '\n<div class="stepwizard margin-bottom-15"><div class="stepwizard-row1 extra-row1">' + html + '\n</div></div>';
                                  html = "";
                                  count = count -4;
                              }
                              html +=  "\n"+$('<div>').append($(this).clone()).html();
                          });
                              final_html += '\n<div class="stepwizard margin-bottom-15"><div class="stepwizard-row1 extra-row1">' + html + '\n</div></div>';
                              $(this).parent().parent().empty().append(final_html)
                              .find(".stepwizard-row1").each(function(){
                                if($(this).children().length == 1){
                                  $(this).addClass("wizard-small-row-element-1");
                              }
                              else if($(this).children().length == 2){
                                  $(this).addClass("wizard-small-row-element-2");
                              }
                              else if($(this).children().length == 3){
                                  $(this).addClass("wizard-small-row-element-3");
                              }
                              else if($(this).children().length == 4){
                                  $(this).addClass("wizard-small-row-element-4");
                              }
                          });
                          });
                        });
//star-script
                        $(function(){
                          $("body").on("change","#skill_modal",function(event,skill){
                              if(skill.selected){
                                $("#skill_rating_group").append("<div id='skill_rating_"+skill.selected+"' class='skill_rating' style='margin-bottom:15px;'><div class='col-md-12' style='padding:0;'><div class='col-md-8 form-label-color margin-top-10' style='padding-left:0;'>"+$('#skill_modal option[value='+skill.selected+']').text()+"</div><div class='cont col-md-4'><div class='stars skill-"+skill.selected+"'><input class='star star-5' id='star-5-"+skill.selected+"' type='radio' name='rating["+skill.selected+"][star]' value='5'/><label class='star star-5' for='star-5-"+skill.selected+"'></label><input class='star star-4' id='star-4-"+skill.selected+"' type='radio' name='rating["+skill.selected+"][star]' value='4'/><label class='star star-4' for='star-4-"+skill.selected+"'></label><input class='star star-3' id='star-3-"+skill.selected+"' type='radio' name='rating["+skill.selected+"][star]' value='3'/><label class='star star-3' for='star-3-"+skill.selected+"'></label><input class='star star-2' id='star-2-"+skill.selected+"' type='radio' name='rating["+skill.selected+"][star]' value='2'/><label class='star star-2' for='star-2-"+skill.selected+"'></label><input class='star star-1' id='star-1-"+skill.selected+"' type='radio' name='rating["+skill.selected+"][star]' value='1'/><label class='star star-1' for='star-1-"+skill.selected+"'></label></div></div></div><div class='clearfix'></div><textarea name='rating["+skill.selected+"][comment]' class='form-control resize-vertical' placeholder='Enter Comment' style='margin-top:10px;min-height:65px;'></textarea><div class='clearfix'></div></div>");

                            }
                            if(skill.deselected){
                                $("#skill_rating_"+skill.deselected).remove();
                            }  
                        });
                      });
                        $(function(){
                            $(".show-hide-btn").on("click",function(){
        // console.log("it's click");        
                                var show_hide_block = $(this).prev(".show-hide-block");
                                show_hide_block.slideToggle("slow",function(){
                                  if ( $(this).is( ":hidden" ) ) {
                                    $(this).next(".show-hide-btn").find("i").removeClass("fa-angle-double-up").addClass("fa-angle-double-down");
                                } else {
                                    $(this).next(".show-hide-btn").find("i").removeClass("fa-angle-double-down").addClass("fa-angle-double-up");
                                }
                            });
                            });
                        });

                        function previewAttachment(el) {
                            var element = $(el).parent();
                            var fileid = $(element).attr('data-file-id');
                            var url = '/messages/attachment/id/'+fileid;
                            $.ajax({
                                type: "POST",
                                url: url,
                                success: function (data) {
                                    previewurl = 'https://docs.google.com/viewer?url='+encodeURIComponent(data)+'&embedded=true';
                                    $("#file"+fileid).attr('href',previewurl) ;
                                    Shadowbox.setup("#file"+fileid);
                                    $("#file"+fileid).get(0).click();

                                }
                            });
    // return true;
                        }
// code for employee search USER ID
                        $(function () {
                            function split(val) {
        return val.split(/,\s*/);
                            }
                            function extractLast(term) {
                                return split(term).pop();
                            }
                            $(document.body)
                // don't navigate away from the field on tab when selecting an item
                            .on("keydown", "#employee-search", function (event) {
                                if (event.keyCode === $.ui.keyCode.TAB &&
                                    $(this).autocomplete("instance").menu.active) {
                                    event.preventDefault();
                            }

                            $(this).autocomplete({
                                source: function (request, response) {
                                    var searchTerm = this.term;
                                    var ids = {};
                                    var url = "/dashboard/GetEmployeesUserId";
                                    $.getJSON(url, {
                                        term: extractLast(searchTerm)
                                    }, response);
                                },
                                search: function () {
                                    var searchTerm = $(this).val();
                                    var term = extractLast(searchTerm);
                                    if (term.length < 2) {
                                        return false;
                                    }
                                },
                                focus: function () {
                            // prevent value inserted on focus
                                    return false;
                                },
                                select: function (event, ui) {
                                    var terms = split(this.value);
                            // remove the current input
                                    terms.pop();
                            // add the selected item
                                    terms.push(ui.item.value);
                            // console.log(ui.item.id);
                                    var a = $("#abc").val();
                                    if (typeof a !== "undefined") {
                                        a = a + ui.item.id + ',';
                                        $("#abc").val(a);
                                    }
                            //console.log(a);
                            // add placeholder to get the comma-and-space at the end
                                    terms.push("");
                                    this.value = terms.join(", ");
                                    return false;
                                },
                                change: function (e, ui) {
                                    if ($(this).val() == '') {
                                        $("#abc").val("");
                                    }
                                }
                            });
                }); // eof autocomplete

    }) // eof function
                        $(document.body)
                        .on("keyup", "#employee-search", function (event) {
                            if ($(this).val() == '') {
                                $("#abc").val("");
                            }
                        });
                        function generateAttendingDataAndFill(id){
                            var response;
                            $.ajax({
                              url: '/vibe/vibe/EventAttedingList/id/'+id,
                              success: function(data){
                                response = JSON.parse(data);
                                $("._sree_modal").find(".modal-title").html('List');
                                $("._sree_modal").find(".modal-body").html('<div class="container"><div class="col-sm-4 sitecolor" id="event_attending"><p class="site-color">Attending:</p></div><div class="col-sm-4" id="event_maybe"><p class="site-color">Not sure:</p></div><div class="col-sm-4" id="event_not_attending"><p class="site-color">Not Attending:</p></div></div>');
                                attending = response.attending;
                                for(var member in attending){
                                  $("#event_attending").append('<p><a href="/employeeprofile/view/id/'+member+'">'+attending[member]+'</a></p>');
                              }
                              if(attending.length == 0)
                                  $("#event_attending").append('N.A');
                              maybe     = response.maybe;
                              for(var member in maybe){
                                  $("#event_maybe").append('<p><a href="/employeeprofile/view/id/'+member+'">'+maybe[member]+'</a></p>');
                              }
                              if(maybe.length == 0)
                                  $("#event_maybe").append('N.A');
                              notAttending = response.notattending;
                              for(var member in notAttending){
                                  $("#event_not_attending").append('<p><a href="/employeeprofile/view/id/'+member+'">'+notAttending[member]+'</a></p>');
                              }
                              if(notAttending.length == 0)
                                  $("#event_not_attending").append('N.A');
                          }
                      })
                        }

                        $(document).ready(function() {
                            $(".sortcol").click(function(){
         featureList = new List("container1", options); // added to update the values once the results are filtered
         name = $(this).attr("sort");
         title_order = $(this).find(".fa-sort, .fa-sort-desc");
         if(typeof title_order.attr("class") != 'undefined') {
           if(name == 'jobcode' || name == 'jobname') {
             featureList.alphabet = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvXxYyZzÅåÄäÖö ";
         }
         featureList.sort(name, {asc: true, alphabet: "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvXxYyZzÅåÄäÖö*"});
         title_order.removeClass("fa-sort").removeClass("fa-sort-desc").addClass("fa-sort-asc");
     }
     else {
       title_order = $(this).find(".fa-sort-asc");
       featureList.sort(name, {asc: false, alphabet: "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvXxYyZzÅåÄäÖö*"});
       title_order.removeClass("fa-sort-asc").addClass("fa-sort-desc");
   }
   $(this).siblings().find(".fa").removeClass("fa-sort-desc").removeClass("fa-sort-asc").addClass("fa-sort");
});
                        });


                        $(document).ready(function() {
                            var new_url_endpoint = "/messages/attachment/id/";
                            $(".vibe-s3-img").error(function() {
                                if(!$(this).attr("fallback-count"))
                                    $(this).attr("fallback-count", 0);
                                else if(parseInt($(this).attr("fallback-count")) > 2)
                                    return;
                                var img_tag = $(this);
                                $.ajax({
                                    url: new_url_endpoint + $(this).parent().attr("data-file-id"),
                                    success: function(data) {
                                        var data = data.trim();
                                        img_tag.attr( "src",  data);
                                        img_tag.attr( "fallback-count",  parseInt(img_tag.attr( "fallback-count")) + 1);
                                    }
                                });
                            });
                        });
                        $(document).ready(function() {
                            $("#export_csv").click(function(){
                                var csvContent = ""
                                if(ordered_list){
                                    var dataString='';
                                    $.each(ordered_list, function(key, value) {
                                        dataString = value+',';
                                        csvContent += dataString;
                                    });
                                    csvContent += "\n";
                                    $.each(err_data,function(key, value){
                                        dataString='';
                                        $.each(ordered_list, function(okey, ovalue) {
                                            var datavalue="";
                                            if(value[okey]!=null && value[okey]!="null")
                                                datavalue=value[okey];
                                            var col_data = '"'+datavalue+'"';
                                            dataString =  col_data +",";
                                            csvContent += dataString;
                                        });
                                        csvContent += "\n";
                                    });
                                }
                                var blobdata = new Blob([csvContent],{type : 'text/csv;charset=utf-8;'});
                                var link = document.createElement("a");
                                link.setAttribute("href", window.URL.createObjectURL(blobdata));
                                link.setAttribute("download", error_filename+"_Error_report.csv");
                                document.body.appendChild(link);
                                link.click();
        //var encodedUri = encodeURI(csvContent);
        //window.open(encodedUri);
                            });
                        });

                        function enableReorderingForTables(identifier, index_selector, additional_functionality, cancelOptions, start_index) {
                            var fixHelperModified = function(e, tr) {
                                var $originals = tr.children();
                                var $helper = tr.clone();
                                $helper.children().each(function(index) {
                                    $(this).width($originals.eq(index).width())
                                });
                                return $helper;
                            },
                            
                            updateIndex = function(e, ui) {
                              if(start_index) {
                                  $(index_selector, ui.item.parent()).each(function (i) {
                                      $(this).html(i + start_index);
                                  });
                              }
                              else {
                                  $(index_selector, ui.item.parent()).each(function (i) {
                                      $(this).html(i + 1);
                                  });
                              }
                              if(additional_functionality) {
                                additional_functionality();
                            }
                        };

                        $(identifier).sortable({
                            helper: fixHelperModified,
                            stop: updateIndex,
                            cancel: cancelOptions
                        }).disableSelection();
                    }

                    function searchEmployeesCompanyWise(identifier, hidden_identifier, grp_cmp_id, singleSelect, restrict = '0'){

                        var is_hrdocs = hidden_identifier == "#abc_hrdocs" ? 1 : 0;
                        $(document.body).on("keydown", identifier, function (event) {
                            if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active) {
                                event.preventDefault();
                            }
                            $(this).autocomplete({
                                source: function (request, response) {
                                    var searchTerm = this.term;
                                    var grpcompsend = grp_cmp_id;
                                    var url = "/dashboard/GetEmployeesUserIdAdmin";
                                    $.getJSON(url, {
                                        term: extractLast(searchTerm),
                                        grpcompsend:grpcompsend,
                                        is_hrdocs:is_hrdocs,
                                        hr_docs_restriction: restrict,
                                    }, response);
                                },
                                search: function () {
                                    var searchTerm = $(this).val();
                                    var term = extractLast(searchTerm);
                                    if (term.length < 2) {
                                        return false;
                                    }
                                },
                                focus: function () {
                // prevent value inserted on focus
                                    return false;
                                },
                                select: function (event, ui) {
                                    var a = $(hidden_identifier).val();
                                    if (typeof a !== "undefined") {
                                        if(!singleSelect){
                                            a = a + ui.item.id.split("_").pop();
                                        } else {
                                            a = ui.item.id.split("_").pop();
                                        }
                                        $(hidden_identifier).val(a);
                                    }
                                    this.value = ui.item.value;
                                    return false;
                                },
                                change: function (e, ui) {
                                    current_val = $(this).val();
                                    if (current_val == "") {
                                        $(hidden_identifier).val("");
                                    }
                                }
                            });
                        });

                        $(document.body).on("keyup", identifier, function (event) {
                            if ($(this).val() == '') {
                                $(hidden_identifier).val("");
                            }
                        });
    /*** Responsive Tabs Js ****/
                        $(document).on('show.bs.tab', '.nav-tabs-responsive [data-toggle="tab"]', function(e) {
                          var $target = $(e.target);
                          var $tabs = $target.closest('.nav-tabs-responsive');
                          var $current = $target.closest('li');
                          var $parent = $current.closest('li.dropdown');
                          $current = $parent.length > 0 ? $parent : $current;
                          var $next = $current.next();
                          var $prev = $current.prev();
                          var updateDropdownMenu = function($el, position){
                            $el
                            .find('.dropdown-menu')
                            .removeClass('pull-xs-left pull-xs-center pull-xs-right')
                            .addClass( 'pull-xs-' + position );
                        };

                        $tabs.find('>li').removeClass('next prev');
                        $prev.addClass('prev');
                        $next.addClass('next');
                        
                        updateDropdownMenu( $prev, 'left' );
                        updateDropdownMenu( $current, 'center' );
                        updateDropdownMenu( $next, 'right' );
                    });

                        $(document).on('click','.show-sub-content',function(){
                            $(this).addClass('hidden');
                            $(this).parent().parent().find('.sub-goals-details').addClass('showDiv');
                            $(this).parents().eq(1).siblings().find('.sub-goals-details').removeClass('showDiv');
                            $(this).parents().eq(1).siblings().find('.show-sub-content').removeClass('hidden');
                        });
                        $(document).on('click','.hide-sub-content',function(){
                            $(this).parents().eq(2).find('.sub-goals-details').removeClass('showDiv');
                            $(this).parents().eq(2).find('.show-sub-content').removeClass('hidden');
                        });
    /*** Responsive Tabs Js End ****/

    /*** Custom Attachment button Js ***/
                        $(function(){
                            $(".uploadBtn").on("change click",function () {
                                var data = $(this).context.files;
                                $(this).parent().find('#filesShowWrapper').html("HEll");
                                $(this).parents().eq(1).find('#filesShowWrapper').html("jjj")
                                if(data.length == 1){
                                 $(this).parents().eq(1).find('#filesShowWrapper')
                                 .html(data[0].name);
                             }
                             else if(data.length > 1){
                              $(this).parents().eq(1).find('#filesShowWrapper')
                              .html(data.length + 'Files Attached');
                          }
                          else{
                              $(this).parents().eq(1).find('#filesShowWrapper').html("No file Chooesn");
                          }

                      });
                        });
    /*** Custom Attachment button Js End ***/


    /*** Ratings Related Js ***/
                        var ids = $('.ratingSelct').map(function() {
                          return $(this).attr('id');
                      });
                        $(function() {
                            for (i = 0; i < ids.length; i++) {
                              var id = ids[i];
                              var currentRating = $('#'+id).data('current-rating');
                              var isReadonly = $('#'+id).data('readonly');
                              $('#'+id).barrating({
                                  theme: 'fontawesome-stars-o',
                                  showSelectedRating: false,
                                  initialRating: currentRating,
                                  readonly: isReadonly,
                              });
                          }   
                      });
                        $('.ratingSelct').change(function(){
                            var ratingText = $(this).find(':selected').data('cont');
                            var ratingValue =  $(this).find(':selected').val();
                            $(this).parents().eq(1).find('.value').text(ratingValue);
                            $(this).parents().eq(1).find('.data-cont').text(ratingText);
                        });
    /*** Ratings Related Js End ***/
                    }

//HR Docs Custom Fields in a page
                    function getHRDocsCustomFieldsInPage(){
                        var custom_fields = {};
                        var fields = $(".custom_field");
                        
                        fields.each(function(){
                            if($(this).prop('nodeName') == 'DIV' && $(this).hasClass("searchabledropdown")) {
                                var field_name = $(this).find('select').attr('custom_field_label').replace("[]", "");
                                var field_id = $(this).find('select').attr('id')
                            } else {
                                var field_name = $(this).attr('custom_field_label').replace("[]", "");
                                var field_id = $(this).attr('id');
                            }

                            if ($("#" + field_id).hasClass("custom_field_checkbox")) {
                                if ($("#" + field_id).is(":checked")) {
                                    var field_value = 1;
                                }
                                else {
                                    var field_value = 0;
                                }
                            }
                            else if ($("#" + field_id).hasClass("custom_field_radio") && !custom_fields[field_name]) {
                                if ($("#" + field_id).is(":checked")) {
                                    var field_value = $("#" + field_id).val();
                                }
                                else {
                                    if (custom_fields[field_name] == undefined || custom_fields[field_name] === "") {
                                        var field_value = "";
                                    }
                                }
                            }
                            else {
                                var field_value = $("#" + field_id).val();
                            }
                            if(!custom_fields[field_name]){
                                custom_fields[field_name] = field_value;
                            }
                        });
                        return custom_fields;
                    }
//HR Docs Custom Fields in a page




// function strip_tags(input, allowed) {
//     if (input == undefined) {
//         return '';
//     }

//     allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
//     var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
//         commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
//     return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1) {
//         return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
//     });
// }
                    $(document).on('click', '.star-five .br-widget a', function() {
                        $(this).addClass('star-clicked');
                        $(this).siblings().removeClass('star-clicked');
                    });

                    $(document).on('keydown','.preventNumber',function(evt){
                        var key = evt.keyCode;
                        if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
                            evt.preventDefault();
                        }
                    });

                    $(document).on('summernote.image.upload','.wysiwyg-editor, #wysiwyg-editor',function(we, files){
                        uploadImageToS3AndGetURL(files[0],$(this));
                    });
                    $(document).on('click', '.btn-fullscreen',function(){
                        if($(".btn-fullscreen").parents().find(".note-btn-bold") != undefined && ($(".btn-fullscreen").parents().find(".note-btn-bold").css("color") == "rgb(1, 115, 197)" || ($(".btn-fullscreen").parents().find(".note-btn-bold").css("color") == "rgb(255, 255, 255)" && $(".btn-fullscreen").parents().find(".note-btn-bold").css("background-color") == "rgb(1, 115, 197)"))){
                            $(this).parents('.note-editor').find('.panel-heading').css({"background-color": "#f5f5f5", "color": "#333", "border-color": "#ddd"});
                        }
                        if($(".note-toolbar-pos").length > 0){
                            if($(this).hasClass("active")){
                                $(this).parents().find(".note-toolbar-wrapper").css({"height":"35px"});
                                $(".note-toolbar-pos").css({"width":$("body").css("width")});
                                $(".note-toolbar-pos").addClass("top-0");
                            } else{
                                $(".note-toolbar-wrapper").css({"height":"0px"});
                                $(".note-toolbar-pos").css({"width":"670px"});
                                $(".note-toolbar-pos").removeClass("top-0");
                            }
                        }
                        if($("#template_max_size").length > 0){
                            if($(this).hasClass("active")){
                                $(".note-toolbar").css({"width":$("body").css("width")});
                                if($("#template_max_size").hasClass("top0")){
                                    $(".note-toolbar").removeClass("top-x").addClass("top-0");
                                }
                            } else{
                                $(".note-toolbar").css({"width":$(".note-editor").css("width")});
                                $(".note-toolbar").css({"position":"relative"});
                                $(".note-toolbar-wrapper").css({"height":"0px"});
                                $(".note-toolbar").css({"top":"0px"});
                                if($("#template_max_size").hasClass("edit-area")){
                                    $(".note-editing-area").css({"top": "0px"});
                                }
                            }
                        }
                    });
                    $(document).on('click','.note-btn',function(e){
                        var img_elem = $(this).find(".note-icon-picture");
                        var link_elem = $(this).find(".note-icon-link");
                        if((img_elem != undefined &&  img_elem.length >0) || (link_elem != undefined && link_elem.length >0)){
                            var elem = $(this).parents().find(".modal");
                            var elem_jd = $(this).parents().find(".jd_particular");
                            if(elem_jd != undefined && elem_jd.length > 0){
                                elem.each(function(index) {
                                    if(!$(this).hasClass("jd_particular")){
                                        $(this).addClass("modalxxx");
                                        $(this).find(".close").attr("data-dismiss","modalxxx");
                                    }
                                });
                            }
                        }
                    });

                    $(document).on('click','.close',function(e){
                        $(".note-children-container").parent().find(".arrow").remove();
                        $(".note-children-container").remove();
                        $(".note-popover").remove();
                    });

                    $(document).keyup(function(e) {
                        if (e.keyCode === 27 && $(".modal-open").length > 0) { 
                            $(".note-children-container").parent().find(".arrow").remove();
                            $(".note-children-container").remove();
                            $(".note-popover").remove();
                            $("body").css({"overflow-y":"auto"});
                        } 
                    });

// this function uploads the image to S3 and adds image with url
                    function uploadImageToS3AndGetURL(file,obj) {
                        var data = new FormData();
                        data.append("file", file);
                        data.append("is_full_object", "1");
    // put image to s3 and add image
                        $.ajax({
                            data: data,
                            type: "POST",
                            url: "/notificationtemplates/uploadImageToS3AndGetUrl",
                            contentType: false,
                            processData: false,
                            success: function(data) {
                                data = JSON.parse(data);
                                if (data.status == "success") {
                // get the url location
                                    var detail = data.url;
                                    var imgLink = detail['ObjectURL']+"?Bucket="+detail['Bucket']+",Key="+detail['Key'];
                // set maximum height and width so that image doesn't overflow edit area.
                var imgNode;// = $('<img style="max-width: 1180px;max-height:600px">').attr('src', imgLink)[0];
                var img = new Image();
                img.onload = function() {
                  //alert(this.width + 'x' + this.height);
                    imgNode = $('<img style="max-width: 1180px;max-height:600px" data-owidth="'+this.width+'">').attr('src', imgLink)[0];
                    obj.summernote('insertNode', imgNode);
                }
                img.src = imgLink;

                // adding image node to editor
            }
            else {
                // error message to notify user about invalid file format
                showNotification({
                    message: data.message,
                    type: "error",
                    autoClose: true,
                    duration: 5,
                });
            }
        },
        error: function(error) {
            alert("There was an error uploading image. Please try again");
            // log the error to console
            console.error(error);
        }
    });
                    }


                    function editorCopiedHtmlConverter(new_content){

                        if(new_content === ''){
                            return new_content;
                        }

                        new_content = new_content.split("&quot;").join("'");

                        new_content = new_content.split("\ufeff").join("");

                        $('body').append('<div class="textEditorDataWrapper hidden">'+new_content+'</div>')
                        
                        $('.textEditorDataWrapper span').each(function(index){
                            if($(this).html().trim().length == 0){
                                $(this).remove();
                            }
                        });

                        new_content = $('.textEditorDataWrapper').html();

                        $('.textEditorDataWrapper').remove();

                        var fullhtml = new_content;

                        var getValue = [];

                        fullhtml.replace(/font-family:((\s|\w|,|-)*(;|"))/g, function (params) { 
                            getValue.push(arguments);
                            return ""
                        });

                        getValue = _.uniq(getValue.map(function(p){return p[1].trim().replace(/;|"/, "")}).reduce(function(acc, q){
                            acc = acc.concat(q.split(",").map(
                                function(r){ return r.trim();})); 
                            return acc
                        }, []));
                        
                        
                        var predefined = [ "Arial", "Calibri", "Times New Roman", "latoregular", "Georgia", "Courier", "Cambria", "Merriweather", "Palatino", "Bookman", "Century Schoolbook", "Roboto", "Roboto Mono", "Garamond", "Devanagri", "Gotham"];

                        var extravalue = _.difference( getValue, predefined);

                        var returndataFlag = 0
                        if(extravalue.length > 0){
                            if (confirm('Font-family not found for copied text, Are you sure you want to continue?')) {
                                returndataFlag = 0;
                            } else {
                                returndataFlag = 1;
                            }
                        }

                        if(returndataFlag == 0){
                            new_content = new_content.replace(/<style type=\"text\/css\"><!--td {border: 1px solid #ccc;}br {mso-data-placement:same-cell;}--><\/style>/g, "");
                            new_content = new_content.replace(/<tr style=\"/g, "<tr table_type=\"formatted\" style=\"border-left: 1px solid black !important;").replace(/<td style=\"/g, "<td table_type=\"formatted\" style=\"border-left: 1px solid black !important;").replace(/<th style=\"/g, "<th table_type=\"formatted\" style=\"border-left: 1px solid black !important;");
                            return new_content;
                        }
                        else{
                            return " ";
                        }
                    }

// Create Base64 Object
// var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/++[++^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}};
                    
                    function previewWorkflowAttachment(el, isSignoffPage = false){
                        var key = $(el).attr('file-key') || $(el).parent().attr('file-key');
                        var bucket = $(el).attr('file-bucket') || $(el).parent().attr('file-bucket');
                        var url = '/separation/previewlink/';
                        var fileParam = 'resource';
                        if (isSignoffPage) {
                            showDocumentForSignOff(url, { key, bucket, name: null }, true);
                        } else {
                            addPreviewAttachmentModal(key,url,fileParam,bucket);
                        }
                    }
                    function previewImage(el){
                        var key = $(el).attr('file-key') || $(el).parent().attr('file-key');
                        var bucket = $(el).attr('file-bucket') || $(el).parent().attr('file-bucket');
                        var url = '/separation/previewlink/';
                        var fileParam = 'resource';
                        addPreviewAttachmentModal(key,url,fileParam,bucket);
                    }
                    
                    function previewCheckInImage(el){
                        var key = $(el).attr('file-key') || $(el).parent().attr('file-key');
                        var bucket = $(el).attr('file-bucket') || $(el).parent().attr('file-bucket');
                        var url = '/separation/previewlink/';
                        var fileParam = 'resource';
                        var is_image = $(el).attr("is_image") || $(el).parent().attr("is_image");
                        addPreviewAttachmentModal(key, url, fileParam, bucket,null,false,false,"",false,{}, is_image);
                    }


                    
                    $(document).on("keydown", ".employee_elastic_search", function (event) {
                        console.log("coming here");
                        if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active) {
                            event.preventDefault();
                        }
                        var $id = $(this).closest(".employee-search-field").find(".name_field").attr("id");
                        $(this).autocomplete({
                            source: function (request, response) {
                                var searchTerm = this.term;
                                var ids = {};
                                var url = "/dashboard/GetEmployeesUserId";
                                $.getJSON(url, {
                                    term: extractLast(searchTerm)
                                }, response);
                            },
                            search: function () {
                                var term = $(this).val();
                                if (term.length < 2) {
                                    return false;
                                }
                            },
                            focus: function () {
            // prevent value inserted on focus
                                return false;
                            },
                            select: function (event, ui) {
                                var terms = split(this.value);
            // remove the current input
                                terms.pop();
            // add the selected item
                                terms.push(ui.item.value);

                                $("#"+$id).val(ui.item.id[0]);
            // add placeholder to get the comma-and-space at the end
                                terms.push("");
                                this.value = terms.join("");
                                return false;
                            },
                            change: function (e, ui) {
                                if ($(this).val() == '') {
                                    $(this).next("#"+$id).val("");
                                }

                            }
                        });
                    });

// Pendo Initialization

                    function pendoInitialize(pendoDetails, userDetails) {
                        var screenResolution = window.screen.width+ 'x' +window.screen.height;
                        if(Array.isArray(pendoDetails) && pendoDetails.length == 0) {
                            window['pendo'].initialize({
                                visitor: {
                                    id : userDetails['subdomain']+ '_' +userDetails['tenant_id']+ '_' +userDetails['user_id'],
                                    screen_resolution: screenResolution
                                },
                                account: {
                                    id: userDetails['subdomain']+ '_' +userDetails['tenant_id'],
                                    subdomain: userDetails['subdomain']
                                }
                            });
                        } else {
                            window['pendo'].initialize({
                                visitor: {
                                    id : userDetails['subdomain']+ '_' +userDetails['tenant_id']+ '_' +userDetails['user_id'],
                                    designation : pendoDetails['designation'],
                                    department : pendoDetails['department'],
                                    office_city : pendoDetails['office_city'],
                                    permission : pendoDetails['is_admin'],
                                    employee_type : pendoDetails['employee_type'],
                                    employee_sub_type : pendoDetails['employee_sub_type'],
                                    functional_area : pendoDetails['functional_area'],
                                    user_language : pendoDetails['language'],
                                    group_company : pendoDetails['group_company_name'],
                                    business_unit : pendoDetails['business_unit'],
                                    division_name : pendoDetails['division_name'],
                                    grade : pendoDetails['grade'],
                                    band : pendoDetails['band'],
                                    job_level : pendoDetails['job_level'],
                                    job_family : pendoDetails['job_family'],
                                    region : pendoDetails['region'],
                                    cost_center : pendoDetails['cost_center'],
                                    payscale_group : pendoDetails['payscale_group'],
                                    location_type : pendoDetails['office_location_type'],
                                    contribution_level : pendoDetails['contribution_level'],
                                    is_hod : pendoDetails['is_hod'],
                                    is_bu_head : pendoDetails['is_bu_head'],
                                    is_functional_head : pendoDetails['is_functional_head'],
                                    is_head_hr : pendoDetails['is_head_hr'],
                                    is_performance_hod : pendoDetails['is_performance_hod'],
                                    is_hrbp : pendoDetails['is_hrbp'],
                                    assignment_one : pendoDetails['assignment_one'],
                                    assignment_two : pendoDetails['assignment_two'],
                                    assignment_three : pendoDetails['assignment_three'],
                                    is_standard_role_one : pendoDetails['is_standard_role1'],
                                    is_standard_role_two : pendoDetails['is_standard_role2'],
                                    is_standard_role_three : pendoDetails['is_standard_role3'],
                                    is_manager : pendoDetails['is_manager'],
                                    is_pms_manager : pendoDetails['is_pms_manager'],
                                    is_dotted_line_manager : pendoDetails['is_dotted_line_manager'],
                                    is_manager_position : pendoDetails['is_manager_position'],
                                    is_hiring_lead : pendoDetails['is_hiring_lead'],
                                    is_recruiter : pendoDetails['is_recruiter'],
                                    screen_resolution: screenResolution
                                },
                                account: {
                                    id: userDetails['subdomain']+ '_' +userDetails['tenant_id'],
                                    active_count : pendoDetails['active_count'],
                // modules : pendoDetails['modules'],
                                    subdomain: userDetails['subdomain']
                                }
                            });
                        }
                    }

// Pendo Initialization

// Onboarding DelayFn
                    var Delayfn=function(callback, ms){
                      var timer = 0;
                      return function() {
                       var context = this, args = arguments;
                       clearTimeout(timer);
                       timer = setTimeout(function () {
                        callback.apply(context, args);
                    }, ms || 0);
                   };
               }

               function getAmplifyField(element) {
                if(element.startsWith("__id__")) {
                    field = element.substr(6);
                    return " [id='"+field+"']"
                } else if(element.startsWith("__class__")) {
                    field = element.substr(9);
                    return " " + field
                } else {
                    return " [name='"+element+"']"
                }
               }

                var amplify_details = {};
               function executeOnload(amplify_script_details=null, sectionSelector="") {
                if(!amplify_script_details)
                    return;
                let rules = amplify_script_details;
                if("transaction_page" in amplify_script_details) {
                    amplify_script_details.sectionSelector = sectionSelector;
                    amplifyServerSideScript(amplify_script_details["transaction_page"]);
                    amplify_details[amplify_script_details["transaction_page"]] = { ...amplify_details[amplify_script_details["transaction_page"]], onLoad: amplify_script_details };
                    if(amplify_script_details["logic_code"]) {
                        rules = (new Function("return " + amplify_script_details["logic_code"]))();
                    } else {
                        return;
                    }
                }
                var notfindingRules = {
                    mandatoryFields: [],
                    nonMandatoryFields: [],
                    dateFields: [],
                    showFields: [],
                    hideFields: [],
                    enableFields: [],
                    disableFields: [],
                    showMessageFieldsLevel: [],
                    clearMessageFieldsLevel: [],
                    applyAlias: [],
                    hideSelectOptions: [],
                    showSelectOptions: [],
                    executeMe: null,
                    makeFieldsReadOnly: [],
                    makeFieldsEditable: [],
                    defaultValues: [],
                }
                if(rules.mandatoryFields) {
                    rules.mandatoryFields.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele)) : $(getAmplifyField(ele));
                        if(elementInFilteredSection && elementInFilteredSection.length) {
                            if(elementInFilteredSection.attr('required') != 'required'){
                                elementInFilteredSection.prop("required", true);
                                var html = "";
                                var htmlWithAstric = "";
                                if(elementInFilteredSection.closest('.amplify-form-group:has(.amplify-form-label), .input-group:has(.amplify-form-label), .form-group:has(.amplify-form-label)').find(".amplify-form-label").length) {
                                    html = elementInFilteredSection.closest('.amplify-form-group:has(.amplify-form-label), .input-group:has(.amplify-form-label), .form-group:has(.amplify-form-label)').find(".amplify-form-label")
                                } else if(elementInFilteredSection.closest('.amplify-form-group:has(label), .input-group:has(label), .form-group:has(label)').find("label").length) {
                                    html = elementInFilteredSection.closest('.amplify-form-group:has(label), .input-group:has(label), .form-group:has(label)').find("label")
                                } else if(elementInFilteredSection.closest('.amplify-form-group:has(.db-label), .input-group:has(.db-label), .form-group:has(.db-label)').find('.db-label').length){
                                    html = elementInFilteredSection.closest('.amplify-form-group:has(.db-label), .input-group:has(.db-label), .form-group:has(.db-label)').find('.db-label')
                                }
                                htmlWithAstric = html.html() + '*';
                                html.html(htmlWithAstric)
                            }
                            if(elementInFilteredSection.hasClass("chosen-filed")) {
                                elementInFilteredSection.trigger("chosen:updated");
                            };
                            elementInFilteredSection.on('keyup input change', function(){
                                checkMandatoryInPageAndDisableSubmits(false,sectionSelector);
                            })
                            sectionSelector = sectionSelector ? sectionSelector : "body";
                            if(elementInFilteredSection.closest(sectionSelector).find('.amplify-submit-button').length) {
                                if(elementInFilteredSection.closest(sectionSelector).find('.amplify-submit-button').prop('tagName') == "A") {
                                    elementInFilteredSection.closest(sectionSelector).find('.amplify-submit-button').addClass("disabled");
                                    elementInFilteredSection.closest(sectionSelector).find('.amplify-submit-button').addClass("prevent-pointer-events");
                                    elementInFilteredSection.closest(sectionSelector).find('.amplify-submit-button').addClass("amplify-anchor-disabled");
                                } else {
                                    elementInFilteredSection.closest(sectionSelector).find('.amplify-submit-button').prop('disabled','disabled');
                                }
                            } else {
                                // elementInFilteredSection.closest('body').find(":submit").prop("disabled", 'disabled');
                                elementInFilteredSection.closest(sectionSelector).find('button[type="submit"]').prop("disabled", 'disabled');
                                elementInFilteredSection.closest(sectionSelector).find('input[type="submit"]').prop("disabled", 'disabled');
                            }
                        } else {
                            notfindingRules.mandatoryFields.push(ele);
                        }
                    });
                }
                if(rules.nonMandatoryFields) {
                    rules.nonMandatoryFields.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele)) : $(getAmplifyField(ele));
                        if(elementInFilteredSection.length && elementInFilteredSection.attr("required")) {
                            elementInFilteredSection.prop("required", false);
                            elementInFilteredSection.removeAttr("required");
                            var html = "";
                            var htmlWithoutAstric = "";
                            if(elementInFilteredSection.closest('.amplify-form-group:has(.amplify-form-label), .input-group:has(.amplify-form-label), .form-group:has(.amplify-form-label)').find(".amplify-form-label").length) {
                                html = elementInFilteredSection.closest('.amplify-form-group:has(.amplify-form-label), .input-group:has(.amplify-form-label), .form-group:has(.amplify-form-label)').find(".amplify-form-label")
                            } else if(elementInFilteredSection.closest('.amplify-form-group:has(label), .input-group:has(label), .form-group:has(label)').find("label").length) {
                                html = elementInFilteredSection.closest('.amplify-form-group:has(label), .input-group:has(label), .form-group:has(label)').find("label")
                            } else if(elementInFilteredSection.closest('.amplify-form-group:has(.db-label), .input-group:has(.db-label), .form-group:has(.db-label)').find('.db-label').length){
                                html = elementInFilteredSection.closest('.amplify-form-group:has(.db-label), .input-group:has(.db-label), .form-group:has(.db-label)').find('.db-label')
                            }
                            htmlWithoutAstric = html.html().replace('*','');
                            html.html(htmlWithoutAstric)
                            if(elementInFilteredSection.hasClass("chosen-filed")) {
                                elementInFilteredSection.trigger("chosen:updated");
                            };
                            elementInFilteredSection.on('keyup input change', function(){
                                checkMandatoryInPageAndDisableSubmits(false,sectionSelector);
                            })
                            sectionSelector = sectionSelector ? sectionSelector : "body";
                            if(elementInFilteredSection.closest(sectionSelector).find('.amplify-submit-button').length) {
                                if(elementInFilteredSection.closest(sectionSelector).find('.amplify-submit-button').prop('tagName') == "A") {
                                    elementInFilteredSection.closest(sectionSelector).find('.amplify-submit-button').addClass("disabled");
                                    elementInFilteredSection.closest(sectionSelector).find('.amplify-submit-button').addClass("prevent-pointer-events");
                                    elementInFilteredSection.closest(sectionSelector).find('.amplify-submit-button').addClass("amplify-anchor-disabled");
                                } else {
                                    elementInFilteredSection.closest(sectionSelector).find('.amplify-submit-button').prop('disabled','disabled');
                                }
                            } else {
                                // elementInFilteredSection.closest('body').find(":submit").prop("disabled", 'disabled');
                                elementInFilteredSection.closest(sectionSelector).find('button[type="submit"]').prop("disabled", 'disabled');
                                elementInFilteredSection.closest(sectionSelector).find('input[type="submit"]').prop("disabled", 'disabled');
                            }
                        } else {
                            notfindingRules.nonMandatoryFields.push(ele);
                        }
                    });
                }
                if(rules.disableFields) {
                    rules.disableFields.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele)) : $(getAmplifyField(ele));
                        if(elementInFilteredSection && elementInFilteredSection.length) {
                            elementInFilteredSection.prop("disabled", 'disabled');
                            if(elementInFilteredSection.hasClass("amplify-elastic-search-input")) {
                                elementInFilteredSection.closest(".amplify-form-group, .input-group, .form-group").addClass("prevent-pointer-events")
                            }
                            if(elementInFilteredSection.hasClass("chosen-filed")) {
                                elementInFilteredSection.trigger("chosen:updated");
                            };
                            if(elementInFilteredSection.closest('.form-group').find('.chosen-container').length){
                                elementInFilteredSection.trigger("chosen:updated");
                            }
                            if(elementInFilteredSection.parent("div").hasClass("searchabledropdown")) {
                                elementInFilteredSection.parent("div").addClass("disabled");
                            };
                            if(elementInFilteredSection.prop('tagName') == "A") {
                                elementInFilteredSection.addClass("prevent-pointer-events");
                                elementInFilteredSection.addClass("amplify-anchor-disabled");
                                elementInFilteredSection.addClass("disabled");
                            }
                            if((elementInFilteredSection.attr('type') == 'submit') || (elementInFilteredSection.hasClass('amplify-submit-button'))) {
                                elementInFilteredSection.addClass('amplify-disabled');
                            }
                        } else {
                            notfindingRules.disableFields.push(ele);
                        }
                    });
                }
                if(rules.dateFields) {
                    rules.dateFields.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele.field)) : $(getAmplifyField(ele.field));
                        if(elementInFilteredSection && elementInFilteredSection.length) {
                           elementInFilteredSection.datepicker("option", {
                                changeMonth: ele.changeMonth,
                                changeYear: ele.changeYear,
                                yearRange: ele.yearRange,
                                minDate: ele.minDate,
                                maxDate: ele.maxDate
                            });
                        } else {
                            notfindingRules.dateFields.push(ele);
                        }
                    });
                }
                if(rules.defaultValues) {
                    rules.defaultValues.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele.field)) : $(getAmplifyField(ele.field));
                        var selector = sectionSelector ? (sectionSelector + getAmplifyField(ele.field)) : (getAmplifyField(ele.field));
                        if($(selector + "input:radio" + "[value='"+ ele.value +"']").length) {
                            if( elementInFilteredSection.closest('.db-switche').length) {
                                elementInFilteredSection.trigger("click");
                            } else {
                                $(selector + "input:radio" + "[value='"+ ele.value +"']").prop("checked",true);
                            }
                        } else if($(selector + "input:checkbox").length){
                            if(ele.value) {
                                if ($(selector  + "input:checkbox" + "[value='"+ ele.value +"']").length) {
                                    if( elementInFilteredSection.closest('.db-switche').length) {
                                        elementInFilteredSection.trigger("click");
                                    } else {
                                        elementInFilteredSection.trigger("click");
                                    }
                                }
                            } else {
                                if(((ele.forcedValue == 1) && !(elementInFilteredSection.prop("checked"))) || ((ele.forcedValue == 0) && (elementInFilteredSection.prop("checked")))) {
                                    elementInFilteredSection.trigger("click");
                                }
                            }
                        } else if(elementInFilteredSection.parent("div").hasClass("searchabledropdown")) {
                            elementInFilteredSection.searchabledropdown("set selected" , ele.value);
                        } else if(elementInFilteredSection.hasClass("timepicker")) {
                            elementInFilteredSection.timepicker("setTime", ele.value);
                        } else if(elementInFilteredSection && elementInFilteredSection.length) {
                            elementInFilteredSection.val(ele.value);
                            if(elementInFilteredSection.hasClass("chosen-filed")) {
                                elementInFilteredSection.trigger("chosen:updated");
                            } else {
                                if(!ele.ignore_trigger) {
                                    elementInFilteredSection.trigger("change");
                                }
                            }
                        } else {
                            notfindingRules.defaultValues.push(ele);
                        }
                        // if(elementInFilteredSection) {
                        //     elementInFilteredSection.trigger("change");
                        // }
                    });
                }
                if(rules.showFields) {
                    rules.showFields.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele)) : $(getAmplifyField(ele));
                        if(elementInFilteredSection && elementInFilteredSection.length) {
                            if(elementInFilteredSection.closest(".amplify-form-group, .input-group, .form-group").length) {
                                if(elementInFilteredSection.closest(".amplify-form-group, .input-group, .form-group").hasClass("amplify-unrestricted-field") && elementInFilteredSection.closest(".amplify-form-group, .input-group, .form-group").hasClass("hidden")) {
                                    elementInFilteredSection.closest('.amplify-form-group, .input-group, .form-group').removeClass("hidden");
                                }
                            }
                            if(elementInFilteredSection.closest('.amplify-form-group').length) {
                                elementInFilteredSection.closest('.amplify-form-group').removeClass('amplify-force-hidden');
                            } else {
                                if(elementInFilteredSection.closest('.input-group, .form-group').length) {
                                    elementInFilteredSection.closest('.input-group, .form-group').removeClass('amplify-force-hidden');
                                }
                                if(elementInFilteredSection.closest('.single_detail').length) {
                                    elementInFilteredSection.closest('.single_detail').removeClass('amplify-force-hidden');
                                }
                                if(!elementInFilteredSection.closest('.form-group').length && !elementInFilteredSection.closest('.input-group').length && !elementInFilteredSection.closest('.single_detail').length && !elementInFilteredSection.closest('.amplify-form-group').length){
                                    elementInFilteredSection.removeClass('amplify-force-hidden');
                                }
                            }
                            // elementInFilteredSection.removeClass('amplify-force-hidden');
                        } else {
                            notfindingRules.showFields.push(ele);
                        }
                    });
                }
                if(rules.hideFields) {
                    rules.hideFields.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele)) : $(getAmplifyField(ele));
                        if(elementInFilteredSection && elementInFilteredSection.length) {
                            if(elementInFilteredSection.closest('.amplify-form-group').length) {
                                elementInFilteredSection.closest('.amplify-form-group').addClass('amplify-force-hidden');
                            } else {
                                if(elementInFilteredSection.closest('.input-group, .form-group').length) {
                                    elementInFilteredSection.closest('.input-group, .form-group').addClass('amplify-force-hidden');
                                }
                                if(elementInFilteredSection.closest('.single_detail').length) {
                                    elementInFilteredSection.closest('.single_detail').addClass('amplify-force-hidden');
                                }
                                if(!elementInFilteredSection.closest('.form-group').length && !elementInFilteredSection.closest('.input-group').length && !elementInFilteredSection.closest('.single_detail').length && !elementInFilteredSection.closest('.amplify-form-group').length){
                                    elementInFilteredSection.addClass('amplify-force-hidden');
                                }
                                // elementInFilteredSection.addClass('amplify-force-hidden');
                            }
                        } else {
                            notfindingRules.hideFields.push(ele);
                        }
                    });
                }
                if(rules.disableFields) {
                    rules.disableFields.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + " [name='"+ele+"']") : $("[name='"+ele+"']");
                        if(elementInFilteredSection && elementInFilteredSection.length) {
                            elementInFilteredSection.prop("disabled", true);
                        } else {
                            notfindingRules.disableFields.push(ele);
                        }
                    });
                }
                if(rules.enableFields) {
                    rules.enableFields.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele)) : $(getAmplifyField(ele));
                        if(elementInFilteredSection && elementInFilteredSection.length) {
                            if (elementInFilteredSection.prop("disabled")) {
                                elementInFilteredSection.prop("disabled", false);
                            }
                            if(elementInFilteredSection.hasClass("amplify-elastic-search-input")) {
                                if(elementInFilteredSection.closest(".tokenfield").hasClass("disabled")) {
                                    elementInFilteredSection.closest(".tokenfield").removeClass("disabled")
                                    if(elementInFilteredSection.closest(".tokenfield").find(".token-input").attr("disabled")) {
                                        elementInFilteredSection.closest(".tokenfield").find(".token-input").removeAttr("disabled")
                                    }
                                }
                                elementInFilteredSection.closest(".amplify-form-group, .input-group, .form-group").removeClass("prevent-pointer-events")
                            }
                            if(elementInFilteredSection.parent("div").hasClass("searchabledropdown")) {
                                elementInFilteredSection.parent("div").removeClass("disabled");
                            }
                            if(elementInFilteredSection.prop('tagName') == "A") {
                                if(elementInFilteredSection.hasClass("amplify-anchor-disabled")) {
                                    elementInFilteredSection.removeClass("prevent-pointer-events");
                                    elementInFilteredSection.removeClass("amplify-anchor-disabled");    
                                }
                                elementInFilteredSection.removeClass("disabled");
                            }
                            if((elementInFilteredSection.attr('type') == 'submit') || (elementInFilteredSection.hasClass('amplify-submit-button'))) {
                                elementInFilteredSection.removeClass('amplify-disabled');
                            }
                            if(elementInFilteredSection.hasClass("chosen-filed")) {
                                elementInFilteredSection.trigger("chosen:updated");
                            }
                            if(elementInFilteredSection.closest('.form-group').find('.chosen-container').length){
                                elementInFilteredSection.trigger("chosen:updated");
                            }
                        } else {
                            notfindingRules.enableFields.push(ele);
                        }
                    });
                }
                if(rules.showMessageFieldsLevel) {
                    rules.showMessageFieldsLevel.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele.field)) : $(getAmplifyField(ele.field));
                        if(elementInFilteredSection && elementInFilteredSection.length) {
                            showMessageUnderField(ele.field, ele.message, ele.type, sectionSelector);
                        } else {
                            notfindingRules.showMessageFieldsLevel.push(ele);
                        }
                    });
                }
                if(rules.clearMessageFieldsLevel) {
                    rules.clearMessageFieldsLevel.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele.field)) : $(getAmplifyField(ele.field));
                        if(elementInFilteredSection && elementInFilteredSection.length) {
                            clearMessageUnderField(ele.field, ele.type, sectionSelector);
                        } else {
                            notfindingRules.clearMessageFieldsLevel.push(ele);
                        }
                    });
                }
                if(rules.applyAlias) {
                    rules.applyAlias.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele.field)) : $(getAmplifyField(ele.field));
                        if(elementInFilteredSection && elementInFilteredSection.length) {
                            applyAliasOn(ele.field, ele.text, ele.type, true, sectionSelector);
                        } else {
                            notfindingRules.applyAlias.push(ele);
                        }
                    });
                }
                if(rules.hideSelectOptions) {
                    rules.hideSelectOptions.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele.field)) : $(getAmplifyField(ele.field));
                        if(elementInFilteredSection && elementInFilteredSection.length) {
                            hideOptionFromSelect(ele.field, ele.values, sectionSelector);
                        } else {
                            notfindingRules.hideSelectOptions.push(ele);
                        }
                    });
                }
                if(rules.showSelectOptions) {
                    rules.showSelectOptions.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele.field)) : $(getAmplifyField(ele.field));
                        var hideOthers = ele.hideOthers ? ele.hideOthers : false;
                        if(elementInFilteredSection && elementInFilteredSection.length) {
                            showOptionFromSelect(ele.field, ele.values, hideOthers, ele.sectionSelector);
                        } else {
                            notfindingRules.showSelectOptions.push(ele);
                        }
                    });
                }
                if(rules.makeFieldsReadOnly) {
                    rules.makeFieldsReadOnly.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele)) : $(getAmplifyField(ele));
                        if(elementInFilteredSection && elementInFilteredSection.length) {
                            elementInFilteredSection.addClass("amplify-make-fields-read-only");
                            if(elementInFilteredSection.hasClass("db-datepicker") || elementInFilteredSection.hasClass("date_picker") || elementInFilteredSection.hasClass("hasDatepicker") || elementInFilteredSection.hasClass("hasDatepicker") || elementInFilteredSection.hasClass("custom_field_date_picker") || (elementInFilteredSection.hasClass("date_picker_etp")) || (elementInFilteredSection.prop("type") == "file") || (elementInFilteredSection.hasClass("amplify-yii-attachment")) || (elementInFilteredSection.hasClass("timepicker"))) {
                                elementInFilteredSection.addClass("prevent-pointer-events");
                                elementInFilteredSection.addClass("amplify-readonly");
                            }
                            else if(elementInFilteredSection.hasClass("amplify-elastic-search-input") || elementInFilteredSection.parent("div").hasClass("searchabledropdown") || elementInFilteredSection.closest('.form-group, .input-group, .amplify-form-group').find('.searchabledropdown, .db-dropdown, .chosen-container, .chosen-filed').length || elementInFilteredSection.closest('.form-group, .input-group, .amplify-form-group').hasClass("chosen-newDesigne")) {
                                elementInFilteredSection.closest(".amplify-form-group, .input-group, .form-group").addClass("prevent-pointer-events")
                            }
                            else if(elementInFilteredSection.parent("div").hasClass("searchabledropdown") || elementInFilteredSection.closest('.form-group, .input-group, .amplify-form-group').find('.searchabledropdown, .db-dropdown, .chosen-container, .chosen-filed, .form-select').length || (elementInFilteredSection.hasClass("form-control") && (elementInFilteredSection.prop("tagName") == "SELECT"))) {
                                elementInFilteredSection.closest('.form-group, .input-group, .amplify-form-group').addClass("prevent-pointer-events");
                            }
                            else if(elementInFilteredSection.hasClass("form-check-input") || elementInFilteredSection.hasClass("upload-file")) {
                                elementInFilteredSection.prop("disabled", "disabled");
                            }
                            else if (elementInFilteredSection.hasClass("form-check-input-custom-field-value")) {
                                if(elementInFilteredSection.attr("type") == 'hidden') {
                                    elementInFilteredSection.closest('.form-group').find(".form-check-input").prop("disabled", "disabled");
                                }
                            }
                            else {
                                elementInFilteredSection.prop("readonly", "readonly");
                            }
                        } else {
                            notfindingRules.makeFieldsReadOnly.push(ele);
                        }
                    });
                }
                if(rules.makeFieldsEditable) {
                    rules.makeFieldsEditable.forEach(function (ele) {
                        var elementInFilteredSection = sectionSelector ? $(sectionSelector + getAmplifyField(ele)) : $(getAmplifyField(ele));
                        if(elementInFilteredSection.hasClass("amplify-make-fields-read-only")) {
                            if(elementInFilteredSection.hasClass("db-datepicker") || elementInFilteredSection.hasClass("date_picker") || elementInFilteredSection.hasClass("timepicker") || elementInFilteredSection.hasClass("hasDatepicker") || elementInFilteredSection.hasClass("hasDatepicker") || (elementInFilteredSection.hasClass("date_picker_etp"))) {
                                if(elementInFilteredSection.hasClass("prevent-pointer-events")) {
                                    elementInFilteredSection.removeClass("prevent-pointer-events");
                                } if(elementInFilteredSection.hasClass("amplify-readonly")) {
                                    elementInFilteredSection.removeClass("amplify-readonly");
                                }
                            }
                            else if(elementInFilteredSection.hasClass("amplify-elastic-search-input") || elementInFilteredSection.parent("div").hasClass("searchabledropdown") || elementInFilteredSection.closest('.form-group, .input-group, .amplify-form-group').find('.searchabledropdown, .db-dropdown, .chosen-container, .chosen-filed').length|| elementInFilteredSection.closest('.form-group, .input-group, .amplify-form-group').hasClass("chosen-newDesigne") || (elementInFilteredSection.hasClass("form-control") && (elementInFilteredSection.prop("tagName") == "SELECT"))) {
                                if(elementInFilteredSection.closest(".amplify-form-group, .input-group, .form-group").hasClass("prevent-pointer-events")) {
                                    elementInFilteredSection.closest(".amplify-form-group, .input-group, .form-group").removeClass("prevent-pointer-events")
                                }
                            }
                            else if(elementInFilteredSection.hasClass("form-check-input") || elementInFilteredSection.hasClass("upload-file")) {
                                if(elementInFilteredSection.prop("disabled")) {
                                    elementInFilteredSection.prop("disabled", false);
                                }
                            }
                            else if (elementInFilteredSection.hasClass("form-check-input-custom-field-value")) {
                                if(elementInFilteredSection.attr("type") == 'hidden') {
                                    if(elementInFilteredSection.closest('.form-group').find(".form-check-input").prop("disabled")) {
                                        elementInFilteredSection.closest('.form-group').find(".form-check-input").prop("disabled", false);
                                    }
                                }
                            }
                            else {
                                if(elementInFilteredSection.prop("readonly")) {
                                    elementInFilteredSection.prop("readonly", false);
                                }
                            }
                        } else {
                            notfindingRules.makeFieldsEditable.push(ele);
                        }
                    });
                }
                if(rules.executeMe && typeof rules.executeMe == 'function') {
                    rules.executeMe();
                }
                
                $(function(){
                    checkMandatoryInPageAndDisableSubmits(false,sectionSelector);
                    // $('input,textarea,select').on('keyup input change', function(){
                    //     checkMandatoryInPageAndDisableSubmits();
                    // })
                    $(document).on('keyup input change', 'input,textarea,select', function () {
                        checkMandatoryInPageAndDisableSubmits();
                    });
                    $(document).on('click', '.amplify-delete-button', function () {
                        $(document).ajaxComplete(function(){
                            checkMandatoryInPageAndDisableSubmits();
                        });
                    });
                    // $('input:required,textarea:required,select:required').on('keyup input change', function(){
                    //     checkMandatoryInPageAndDisableSubmits();
                    // })
                });
            }
            function checkMandatoryInPageAndDisableSubmits(returnIsPendingMandatory = false, sectionSelector=""){
                    var check_any_mandory_is_pending = $(`${sectionSelector} input:required,${sectionSelector} textarea:required,${sectionSelector} select:required`).filter(function(){                    // console.log('---', $(this), $(this).val());
                    // if($(this).closest('.hidden').length || $(this).val()) {
                    if((($(this).prop("type") == "checkbox") && ($(this).prop("checked") == true)) || (($(this).hasClass('hidden').length || $(this).parent('.hidden').length || ($(this).closest('.hidden').length && !$(this).closest('.hidden').hasClass('eachFieldContainer')) || ($(this).filter("[type='hidden']").length) || ($(this).closest(".form-group").find(".amplify-attachment-data").children().length)) && !sectionSelector) || (($(this).prop("type") != "checkbox") && $(this).val() && $(this).val().length && (!($(this).closest(".form-group").find(".amplify-attachment-data").length)))) {
                        return false;
                    } else {
                        return true;
                    }
                });
                if(returnIsPendingMandatory) {
                    return check_any_mandory_is_pending.length ? true : false;
                }
                sectionSelector = sectionSelector ? sectionSelector : "body";
                if(check_any_mandory_is_pending.length) {
                    if($(sectionSelector).find('.amplify-submit-button').length) {
                        if($(sectionSelector).find('.amplify-submit-button').prop('tagName') == "A") {
                            $(sectionSelector).find('.amplify-submit-button').addClass("disabled");
                            $(sectionSelector).find('.amplify-submit-button').addClass("prevent-pointer-events");
                            $(sectionSelector).find('.amplify-submit-button').addClass("amplify-anchor-disabled");
                        } else {
                            $(sectionSelector).find('.amplify-submit-button').prop('disabled','disabled');
                        }
                    }
                    else {
                        sectionSelector = sectionSelector ? sectionSelector : "body";
                        $(sectionSelector).find('button[type="submit"]').prop("disabled", 'disabled');
                        $(sectionSelector).find('input[type="submit"]').prop("disabled", 'disabled');
                    }
                } else {
                    $(sectionSelector).find('button[type="submit"]').not('.amplify-disabled').prop("disabled", false);
                    $(sectionSelector).find('input[type="submit"]').not('.amplify-disabled').prop("disabled", false);
                    $(sectionSelector).find('.amplify-submit-button').not('.amplify-disabled').prop('disabled',false);
                    if(($(sectionSelector).find('.amplify-submit-button').hasClass("disabled")) && ($(sectionSelector).find('.amplify-submit-button').hasClass("amplify-anchor-disabled")) && ($(sectionSelector).find('.amplify-submit-button').not('.amplify-disabled').length)) {
                        $(sectionSelector).find('.amplify-submit-button').removeClass("disabled");
                        $(sectionSelector).find('.amplify-submit-button').removeClass("prevent-pointer-events");
                        $(sectionSelector).find('.amplify-submit-button').removeClass("amplify-anchor-disabled");
                    }
                
                }
            }

            $.fn.bindFirst = function(name, fn, ele) {
                this.on(name, fn.bind({ele}));
                this.each(function() {
                    var handlers = $._data(this, 'events')[name.split('.')[0]];
                    var handler = handlers.pop();
                    handlers.splice(0, 0, handler);
                });
            };
            
            $.fn.bindLast = function(name, fn, event, ele) {
                event.stopImmediatePropagation();
                // this.on(name, fn);
                this.on(name, fn.bind({ele}));
                this.each(function() {
                    var handlers = $._data(this, 'events')[name.split('.')[0]];
                    handlers.shift();
                });
                this.trigger(name);
            };

            function handleExecuteOnchange(amplify_script_details, sectionSelector="") {
                if(!amplify_script_details) {
                    return;
                }
                let rules = amplify_script_details;
                if("transaction_page" in amplify_script_details) {
                    amplify_script_details.sectionSelector = sectionSelector;
                    amplify_details[amplify_script_details["transaction_page"]] = { ...amplify_details[amplify_script_details["transaction_page"]], onChange: amplify_script_details };
                    if(amplify_script_details["logic_code"]) {
                        rules = (new Function("return " + amplify_script_details["logic_code"]))();
                    } else {
                        return;
                    }
                }
                if(rules && rules.length) {
                    rules.forEach(function(ele){
                        var fieldName = ele.field_name;
                        if(fieldName.startsWith("__id__")) {
                            fieldCheck = fieldName.substr(6);
                            amplify_field_check = " [id='"+fieldCheck+"']"
                            amplify_field_check_change = ' [id=\''+fieldCheck+'\']'
                        } else if(fieldName.startsWith("__class__")) {
                            fieldCheck = fieldName.substr(9);
                            amplify_field_check = " " + fieldCheck
                            amplify_field_check_change = " " + fieldCheck
                        } else {
                            amplify_field_check = " [name='"+fieldName+"']"
                            amplify_field_check_change = ' [name=\''+fieldName+'\']'
                        }
                        if(ele.executeOnchange) {
                            if($(sectionSelector+amplify_field_check).length && ele.setPriority) {
                                $(amplify_field_check).bindFirst('change', function (event) {
                                    if(ele.setPriority == 1) {
                                        if(ele.execute_on_data_load == true) {
                                            var amplify_load_check_flag = true;
                                            $(document).ajaxStop(function(){
                                                console.log("All AJAX requests completed");
                                                if(amplify_load_check_flag) {
                                                    setTimeout(() => {
                                                        ele.executeOnchange(sectionSelector); 
                                                    }, 400);
                                                    amplify_load_check_flag = false;
                                                }
                                            });
                                        } else {
                                            ele.executeOnchange(sectionSelector);
                                        }
                                    } else if (ele.setPriority == 2){
                                        $(this).bindLast('change', function(){
                                            if(ele.execute_on_data_load == true) {
                                                var amplify_load_check_flag = true;
                                                $(document).ajaxStop(function(){
                                                    console.log("All AJAX requests completed");
                                                    if(amplify_load_check_flag) {
                                                        setTimeout(() => {
                                                            ele.executeOnchange(sectionSelector); 
                                                        }, 400);
                                                        amplify_load_check_flag = false;
                                                    }
                                                });
                                            } else {
                                                ele.executeOnchange(sectionSelector);
                                            }
                                        },event,ele)
                                    }
                                }, ele);
                            } else {
                                $(document).on('change', '*'+sectionSelector+amplify_field_check_change, function () { 
                                    if(ele.execute_on_data_load == true) {
                                        var amplify_load_check_flag = true;
                                        $(document).ajaxStop(function(){
                                            console.log("All AJAX requests completed");
                                            if(amplify_load_check_flag) {
                                                setTimeout(() => {
                                                    ele.executeOnchange(sectionSelector); 
                                                }, 400);
                                                amplify_load_check_flag = false;
                                            }
                                        });
                                    } else {
                                        ele.executeOnchange(sectionSelector);
                                    }
                                });
                                if(dbxfield(fieldName)) {
                                    $(sectionSelector+amplify_field_check).trigger('change');
                                }
                            }
                        }
                        if(ele.executeOnclick) {
                            if($(sectionSelector+amplify_field_check).length && ele.setPriority) {
                                    $(sectionSelector+amplify_field_check).bindFirst('click', function (event) {
                                        if(ele.setPriority == 1) {
                                            if(ele.execute_on_data_load == true) {
                                                var amplify_load_check_flag = true;
                                                $(document).ajaxStop(function(){
                                                    console.log("All AJAX requests completed");
                                                    if(amplify_load_check_flag) {
                                                        setTimeout(() => {
                                                            ele.executeOnclick(sectionSelector); 
                                                        }, 400);
                                                        amplify_load_check_flag = false;
                                                    }
                                                });
                                            } else {
                                                ele.executeOnclick(sectionSelector);
                                            }
                                        } else if (ele.setPriority == 2){
                                            $(sectionSelector+this).bindLast('click', function(){
                                                if(ele.execute_on_data_load == true) {
                                                    var amplify_load_check_flag = true;
                                                    $(document).ajaxStop(function(){
                                                        console.log("All AJAX requests completed");
                                                        if(amplify_load_check_flag) {
                                                            setTimeout(() => {
                                                                ele.executeOnclick(sectionSelector); 
                                                            }, 400);
                                                            amplify_load_check_flag = false;
                                                        }
                                                });
                                            } else {
                                                ele.executeOnclick(sectionSelector);
                                            }
                                        },event,ele)
                                    }
                                }, ele);
                            } else {
                                $(document).on('click', '*'+sectionSelector+amplify_field_check_change, function () {
                                    if(ele.execute_on_data_load == true) {
                                        var amplify_load_check_flag = true;
                                        $(document).ajaxStop(function(){
                                            console.log("All AJAX requests completed");
                                            if(amplify_load_check_flag) {
                                                setTimeout(() => {
                                                    ele.executeOnclick(sectionSelector); 
                                                }, 400);
                                                amplify_load_check_flag = false;
                                            }
                                        });
                                    } else {
                                        ele.executeOnclick(sectionSelector);
                                    }
                                });
                            }
                        }
                    })
                }
            }


            function dbxfield(fieldName, sectionSelector = "", returnOption = ""){
                const actualField = sectionSelector ? $(sectionSelector + getAmplifyField(fieldName)) : $(getAmplifyField(fieldName));
                if(actualField.length) {
                    if(returnOption == "isChecked") {
                        return actualField.is(":checked") ? "checked" : "unchecked";
                    }
                    if(actualField.prop("type") == "radio") {
                        return $("[name='" + fieldName + "']:checked").val();
                    }
                    return actualField.val() ? actualField.val() : actualField.data( "amplify-value" );
                } else {
                    return '';
                }
            }

            function dbxfieldText(fieldName, type='', sectionSelector = ""){
                const actualField = sectionSelector ? $(sectionSelector + getAmplifyField(fieldName)) : $(getAmplifyField(fieldName));
                if(actualField.length) {
                    if(type && type == 'select') {
                        let values = actualField.val();
                        if(Array.isArray(values)) {
                            let results = [];
                            values.forEach((eachValue)=> {
                                if(actualField.children().closest("optgroup").length) {
                                    results.push(actualField.children().closest("optgroup").children("option[value='"+ eachValue +"']").html());
                                } else {
                                    results.push(actualField.children("option[value='"+ eachValue +"']").html());
                                }
                            });
                            return results;
                        } else {
                            if(actualField.children().closest("optgroup").length) {
                                return actualField.children().closest("optgroup").children("option[value='"+ values +"']").html();
                            } else {
                                return actualField.children("option[value='"+ values +"']").html();
                            }
                        }
                    } else {
                        return actualField.html();
                    }
                } else {
                    return '';
                }
            }

            function showNotificationOnTop(message='', type='success', duration=5){
                showNotification({
                    message: message,
                    type: type,
                    autoClose: true,
                    duration: duration
                });
            }

            function showMessageUnderField(fieldName='', message='', type='success', sectionSelector = ""){
                var actualField = sectionSelector ? $(sectionSelector + getAmplifyField(fieldName)) : $(getAmplifyField(fieldName));
                if(actualField.length) { 
                    if(type == 'error') {
                        if (actualField.closest('.amplify-table-row').length) {
                            actualField.closest('.amplify-table-row').append('<span class="db-error-msg db-amplify-msg wrap-text clear-both" id="error-msg-fieldName">'+message+'</span>');
                        } else if (actualField.closest('.amplify-form-group, .form-group, .input-group').length) {
                            actualField.closest('.amplify-form-group, .form-group, .input-group').addClass('display-block').append('<span class="db-error-msg db-amplify-msg wrap-text clear-both" id="error-msg-fieldName">'+message+'</span>');
                        }
                    } else if(type == 'success') {
                        if (actualField.closest('.amplify-table-row').length) {
                            actualField.closest('.amplify-table-row').append('<span class="db-success-msg db-amplify-msg wrap-text clear-both" id="success-msg-fieldName">'+message+'</span>');
                        } else if (actualField.closest('.amplify-form-group, .form-group, .input-group').length) {
                            actualField.closest('.amplify-form-group, .form-group, .input-group').addClass('display-block').append('<span class="db-success-msg db-amplify-msg wrap-text clear-both" id="success-msg-fieldName">'+message+'</span>');
                        }
                    }
                }
                
            }

            function clearMessageUnderField(fieldName, type, sectionSelector = ""){
                var actualField = sectionSelector ? $(sectionSelector + getAmplifyField(fieldName)) : $(getAmplifyField(fieldName));
                if(actualField.length) { 
                    if(type == 'error') {
                        if (actualField.closest('.amplify-form-group').length) {
                            actualField.closest('.amplify-form-group').children('.db-error-msg.db-amplify-msg').remove();
                        } else if(actualField.closest('.form-group, .input-group').length) {
                            actualField.closest('.form-group, .input-group').children('.db-error-msg.db-amplify-msg').remove();
                        }
                    } else if(type == 'success') {
                        if (actualField.closest('.amplify-form-group').length) {
                            actualField.closest('.amplify-form-group').children('.db-success-msg.db-amplify-msg').remove();
                        } else if(actualField.closest('.form-group, .input-group').length) {
                            actualField.closest('.form-group, .input-group').children('.db-success-msg.db-amplify-msg').remove();
                        }
                    }
                }
            }

            function clearAllFieldLevelMessage(type){
                if(type == 'error') {
                    $('body').find('.db-error-msg.db-amplify-msg').remove();
                } else if(type == 'success') {
                    $('body').find('.db-success-msg.db-amplify-msg').remove();
                } else {
                    $('body').find('.db-amplify-msg').remove();
                }
            }

            function applyAliasOn(fieldName, text, place='', replaceOld=true, sectionSelector = ""){
                const actualField = sectionSelector ? $(sectionSelector + getAmplifyField(fieldName)) : $(getAmplifyField(fieldName));
                type = actualField.prop("tagName");
                if(actualField.length) {
                    if(text) {
                        if(place == 'label') {
                            if(actualField.closest('.amplify-form-group:has(.amplify-form-label), .input-group:has(.amplify-form-label), .form-group:has(.amplify-form-label)').find('.amplify-form-label').length) {
                                replaceOld ? actualField.closest('.amplify-form-group:has(.amplify-form-label), .input-group:has(.amplify-form-label), .form-group:has(.amplify-form-label)').find('.amplify-form-label').html(text) : actualField.closest('.amplify-form-group:has(.amplify-form-label), .input-group:has(.amplify-form-label), .form-group:has(.amplify-form-label)').find('.amplify-form-label').append(text);
                            } else if(actualField.closest('.amplify-form-group:has(label), .input-group:has(label), .form-group:has(label)').find('label').length) {
                                replaceOld ? actualField.closest('.amplify-form-group:has(label), .input-group:has(label), .form-group:has(label)').find('label').html(text) : actualField.closest('.amplify-form-group:has(label), .input-group:has(label), .form-group:has(label)').find('label').append(text);
                            } else {
                                replaceOld ? actualField.closest('.amplify-form-group:has(.db-label), .input-group:has(.db-label), .form-group:has(.db-label)').find('.db-label').html(text) : actualField.closest('.amplify-form-group:has(.db-label), .input-group:has(.db-label), .form-group:has(.db-label)').find('.db-label').append(text);
                            }
                        } else {
                            if (type == 'INPUT') {
                                replaceOld ? actualField.val(text) : actualField.val(actualField.val() + text);
                            } else {
                                replaceOld ? actualField.html(text) : actualField.append(text);
                            }
                        }
                    }
                }
            }

            function hideOptionFromSelect(fieldName, values=[], sectionSelector = ""){
                const actualField = sectionSelector ? $(sectionSelector + getAmplifyField(fieldName)) : $(getAmplifyField(fieldName));
                values.forEach((eachValue)=> {
                    actualField.closest('.db-dropdown').find('.menu').children("[data-value='"+ eachValue +"']").addClass('hidden disabled');
                    if(actualField.children().closest("optgroup").length) {
                        actualField.children().closest("optgroup").children("option[value='"+ eachValue +"']").addClass('hidden disabled');
                    } else {
                        actualField.children("option[value='"+ eachValue +"']").addClass('hidden disabled');
                    }
                });
                var selectOption = actualField.closest('.db-dropdown').find('.menu').children().not(".hidden").attr("data-value");
                if(selectOption) {
                    actualField.searchabledropdown("set selected", selectOption);
                }
                if(actualField.closest('.amplify-form-group').find('.chosen-container').length){
                    actualField.trigger("chosen:updated");
                } else if(actualField.closest('.form-group').find('.chosen-container').length){
                    actualField.trigger("chosen:updated");
                } else if(actualField.closest('.input-group').find('.chosen-container').length) {
                    actualField.trigger("chosen:updated");
                } if(actualField.closest('.input-group').find('.chosen-container').length){
                    actualField.trigger("chosen:updated");
                }
            }

            function showOptionFromSelect(fieldName, values=[], hideOthers=false, sectionSelector = ""){
                const actualField = sectionSelector ? $(sectionSelector + getAmplifyField(fieldName)) : $(getAmplifyField(fieldName));
                if(hideOthers) {
                    actualField.closest('.db-dropdown').find('.menu').children().addClass('hidden');
                    if(actualField.children().closest("optgroup").length) {
                        actualField.children().closest("optgroup").children().addClass('hidden');
                    } else {
                        actualField.children().addClass('hidden');
                    }
                }
                values.forEach((eachValue)=> {
                    actualField.closest('.db-dropdown').find('.menu').children("[data-value='"+ eachValue +"']").removeClass('hidden disabled');
                    if(actualField.children().closest("optgroup").length) {
                        actualField.children().closest("optgroup").children("option[value='"+ eachValue +"']").removeClass('hidden disabled');
                    } else {
                        actualField.children("option[value='"+ eachValue +"']").removeClass('hidden disabled');
                    }
                });
                var selectOption = actualField.closest('.db-dropdown').find('.menu').children().not(".hidden").attr("data-value");
                if(selectOption) {
                    actualField.searchabledropdown("set selected", selectOption);
                }
                if(actualField.closest('.amplify-form-group').find('.chosen-container').length){
                    actualField.trigger("chosen:updated");
                } else if(actualField.closest('.form-group').find('.chosen-container').length){
                    actualField.trigger("chosen:updated");
                } else if(actualField.closest('.input-group').find('.chosen-container').length) {
                    actualField.trigger("chosen:updated");
                } if(actualField.closest('.input-group').find('.chosen-container').length){
                    actualField.trigger("chosen:updated");
                }
            }

            function fetchDbxData(input_data={}, output_data={}, callback=function(d){}, queryPath='/studio/amplifyscripts/index') {
                params = []
                params["input_data"] = input_data["input_data"]
                params["output_data"] = output_data["output_data"]
                $.ajax({
                    url: queryPath,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        ...params
                    },
                    success: function (result) {
                        callback(result);
                    }
                });
            }

            function fetchDbxLookupData(input_data={}, output_data={}, callback=function(d){}, queryPath='/studio/amplifyscripts/fetchDbxLookupData') {
                params = []
                params["input_data"] = input_data["input_data"]
                params["output_data"] = output_data["output_data"]
                $.ajax({
                    url: queryPath,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        ...params
                    },
                    success: function (result) {
                        callback(result);
                    }
                });
            }

$(document).on("click",".requested_letter_check",function(){
    var closestDiv = $(this).closest('div');
    var requestedDivId = closestDiv.attr('id');
    var requestId = requestedDivId.split("_")[1];
    softWarningCheck(requestId);
});

function hex2(c) {
    c = Math.round(c);
    if (c < 0) c = 0;
    if (c > 255) c = 255;

    var s = c.toString(16);
    if (s.length < 2) s = "0" + s;

    return s;
}

function color(r, g, b) {
    return "#" + hex2(r) + hex2(g) + hex2(b);
}

function shade(col, light, variable) {

    // TODO: Assert that col is good and that -1 < light < 1

    var r = parseInt(col.substr(1, 2), 16);
    var g = parseInt(col.substr(3, 2), 16);
    var b = parseInt(col.substr(5, 2), 16);

    if (light < 0) {
        r = (1 + light) * r;
        g = (1 + light) * g;
        b = (1 + light) * b;
    } else {
        r = (1 - light) * r + light * 255;
        g = (1 - light) * g + light * 255;
        b = (1 - light) * b + light * 255;
    }

    document.documentElement.style.setProperty(variable, color(r, g, b));
}

$(document).on("click",".requested_letter_check_expand",function(){
    var closestAnchor = $(this).closest('a');
    var requestId = closestAnchor.attr('id');
    softWarningCheck(requestId);
});

function softWarningCheck(requestId){
    var data = {
        request_id: requestId
    }
    $.ajax({
        type: "POST",
        dataType: "json",
        data: data,
        url: "/hrfiles/hrfiles/checkLetterIsAlreadyGeneratedforUser",
        success: function(data) {
            if(data.status == "success" && data.message != ""){
                if(confirm(data.message)){
                    window.open("/hrfiles/hrfiles/renderLetter/id/"+requestId+"/mode/ACT", '_blank');    
                }else{
                    $.ajax({
                        type: "POST",
                        data: {id:requestId,action: '3', comment: "Defalut Message"},
                        dataType: "json",
                        url: "/messages/RequestProcess",
                        success: function(data) {
                        if(data.status =="success"){
                            $("#book_" + requestId).html(data.update);
                                                        // Hide Slider
                            $("#book_"+ requestId).hide();
                                                        // Change color
                            $("#request_thread_"+requestId).attr("class", "alert alert-success clearfix requestDiv");
                        }else{
                            showNotification({
                                message: data.error,
                                type: "error",
                                autoClose: true,
                                duration: ' . AllRequest::LIMIT . '
                                });
                            }
                        }
                    })
                }
            }else{
                window.open("/hrfiles/hrfiles/renderLetter/id/"+requestId+"/mode/ACT", '_blank');
            }
        }
    });
}
function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}
function allowPasteNumberOnly(e) {
    e.preventDefault();
    const paste = (e.originalEvent || e).clipboardData.getData("text");
    if (/^\d+$/.test(paste)) {
        document.execCommand("insertText", false, paste);
    }
}
function addSufficientMarginBottom(conatiner) {
    const timer = setInterval(()=>{
        const scrollHeight = document.querySelector(conatiner).scrollHeight;
        const clientHeight = document.querySelector(conatiner).clientHeight;
        if(scrollHeight > clientHeight){
            $(conatiner).css("margin-bottom", `${scrollHeight+24-clientHeight}px`);
        }
    },100);
    setTimeout(() => {
        clearInterval(timer);
    }, 500);
}
function unSetMarginBottom(conatiner) {
    setTimeout(()=>{
        $(conatiner).css("margin-bottom", "unset")
    },400)
}