<div class="modal fade" id="add-edit-role-permissions-modal" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="add-label h-labels text-left bold hidden"><?php echo CommonLanguage::getMessage('add_role_permissions');?></h5>
                <h5 class="edit-label h-labels text-left bold hidden"><?php echo CommonLanguage::getMessage('edit_role_permissions');?></h5>
                <h5 class="copy-label h-labels text-left bold hidden"><?php echo CommonLanguage::getMessage('copy_role_permissions');?></h5>
            </div>
            <div class="modal-body">
                <form id="role_permission_form" method="POST" onsubmit="return false">
                    <input type='hidden' name='Role_ID' id='Role_ID'/>
                    <div class="row">
                        <?php echo Forms::AlertDiv('role_permission_alert'); ?>
                    </div>
                    <div class="row">
                        <div class="col-md-3 form-group m-t-10">
                            <label><?php print CommonLanguage::getMessage('role'); ?></label>
                            <span class="red-star">*</span>
                            <input type="text"  placeholder="<?php print CommonLanguage::getMessage('role'); ?>" id="Role_Name" name="Role_Name" class="form-control " required>
                        </div>
                        <div class="col-md-3 form-group m-t-10 parent_role_div">
                            <label><?php print CommonLanguage::getMessage('parent_role_name'); ?></label>
                            <span class="red-star">*</span>
                            <input type="hidden" id="Parent_ID" name="Parent_ID" class="full-width" required>
                        </div>
                    </div>
                    <div class="row" id="DataTree">
                        <div class="col-md-12">
                            <div role="tabpanel">
                                <ul class="nav nav-tabs nav-tabs-simple" role="tablist">
                                </ul>      
                            </div>
                            <div class="tab-content">
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close'); ?></button>
                <button class="btn bg-info-light text-white" id="submit_role_permission"><?php print CommonLanguage::getMessage('Save'); ?></button>
            </div>
            <?php echo Forms::ModalLoader('rolePermissionLoader'); ?>
        </div>
    </div>
</div>
<div class="modal fade" id="DeleteFromList">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="add-label bold text-left"><?php echo CommonLanguage::getMessage('Confirm_Delete'); ?></h5>
            </div>
            <div class="modal-body">
                <div class="row">
                    <?php echo Forms::AlertDiv('DeleteCustomer_modalAlert'); ?>
                </div>
                <div class="row">
                    <div class="col-md-12 ">
                        <div class="col-md-12" style="margin-top: 20px;">
                            <p><?php print CommonLanguage::getMessage('About_Delete') ?> <strong class="Name"></strong></p>
                            <p><?php print CommonLanguage::getMessage('Proceed_Delete') ?></p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close') ?></button>
                <button type="button" class="btn btn-danger width-auto" id="Role_Delete" ><?php print CommonLanguage::getMessage('delete') ?></button>
            </div>
        </div>
    </div>
</div>
<script>
        var RolePermation_ToDelete;
                                 var       Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>;
    $(function(){
        build_select2($("#Parent_ID"), "xhr/getRelatedRoles");
        $("#add-role-permissions").on("click", function () {
            $("#Role_ID").val(0);
            $('#DataTree .tab-content,#DataTree ul').empty();
            $("#add-edit-role-permissions-modal .add-label,#add-edit-role-permissions-modal .parent_role_div").removeClass('hidden');
        });
        var RolePermation_ToDelete;
        $("#tableWithSearch").on("click", ".Action .delete_role_permissions", function () {
                    //alert("OK")
                    var me = $(this).parents("tr");
                    var name = me.find("td:eq(0)").text();
                    $("#DeleteFromList").find(".Name").text(name).end().modal("show")
                    RolePermation_ToDelete = $(this).parents("tr").find('.Action').attr('data-id')
         });
         $("#Role_Delete").on("click", function () {
                    $.ajax({
                        type: 'GET',
                        url: 'SettingsAjax/deleteRolePermation',
                        data: {GetRoleID: RolePermation_ToDelete},
                        complete: function (data, vv) {
                            console.log('data')
                            console.log(data)
                            if (vv == "success") {
                                if (data.responseText == 'OK') {
                                    AddAlert("#DeleteCustomer_modalAlert", Submitted_Successfully, 'success');
                                    RebuildDataTable($('.panel-heading .panel-title').html(), [0, 1, 2], 'SettingsAjax/getRoles');
                                    hideModalAlert('DeleteFromList', 'DeleteCustomer_modalAlert');
                                } else {
                                    AddAlert("#DeleteCustomer_modalAlert", data.responseText, 'danger');
                                }
                            }
                        }
                    });
                });
        $("#tableWithSearch").on("click", ".edit_role_permissions,.copy_role_permissions", function () {
            var role_id = $(this).parents('div.Action').attr('data-id'),
                type=$(this).attr('data-type');
            $('#submit_role_permission').attr('disabled',true);
            if(type =='edit'){
                $("#Role_ID").val(role_id);
                $("#add-edit-role-permissions-modal .edit-label").removeClass('hidden'); 
            }else{
                $("#Role_ID").val(0);
                $("#add-edit-role-permissions-modal .copy-label").removeClass('hidden');
            }

            $('#DataTree .tab-content,#DataTree ul').empty();
            CommonViewById('SettingsAjax/getPermissionsByRole',{role_id:role_id},
                           '#rolePermissionLoader',function(response){
                var main_details = response['main'][0],permissions= response['perm'];
                $('#Parent_ID').val(main_details.Parent_ID);
                $('#Parent_ID').attr('data-select-name',main_details.parent_role_name);
                main_details.Parent_ID == 0 ?  $("#add-edit-role-permissions-modal .parent_role_div").addClass('hidden') :  $("#add-edit-role-permissions-modal .parent_role_div").removeClass('hidden');
                build_select2($("#Parent_ID"), "xhr/getRelatedRoles");
                if(type == 'edit'){
                    $('#Role_Name').val(main_details.Role_Name);
                }
                buildRolePermissionsTree(permissions);
            });
        }); 
        $('#Parent_ID').on('change',function(){
            $('#DataTree .tab-content,#DataTree ul').empty();
            if($('#Parent_ID').val()){
                buildRolePermissionsTree([]);
            }
        });
        $('#DataTree').on('click','.tree .dynatree-title',function(){
            var parent = $(this).parents('.tree'),current_tree = parent.dynatree("getTree"),
                active_node = parent.dynatree("getActiveNode");
            if(!active_node.isSelected()){
                recursive_check_selected(active_node);
            }else{
                active_node.select(false);
            }
        });
        $("#submit_role_permission").on("click", function () {
            if (!$("#role_permission_form").valid())
                return;
            var Data = new FormData(document.getElementById("role_permission_form")),Per = [];
            $(".tree").each(function () {
                var tree = $(this).dynatree("getTree"),selectedNodes = tree.getSelectedNodes(false);
                for (var j = 0; j < selectedNodes.length; i++, j++) {
                    Per[i] = selectedNodes[j].data.key;
                }
            });
            if(Per.length == 0){
                AddAlert("#role_permission_alert", '<?php echo CommonLanguage::getMessage('choose_permissions_to_assign');?>', "danger");
                return;
            }
            Data.append('Per',JSON.stringify(Per));
            $("#rolePermissionLoader").removeClass('hidden');
            $.ajax({
                url: "SettingsAjax/submitRolePermissions",
                method: "POST",
                data: Data,
                processData: false,
                contentType: false,
                dataType: "JSON",
                complete: function (jqXHR, status) {
                    if (status == 'success') {
                        if (jqXHR.responseJSON[1] == "success") {
                            RebuildDataTable($('.panel-heading .panel-title').html(), [0, 1, 2], 'SettingsAjax/getRoles');
                            hideModalAlert('add-edit-role-permissions-modal', 'role_permission_alert');
                            $('#DataTree .tab-content,#DataTree ul').empty();
                        }
                        AddAlert("#role_permission_alert", jqXHR.responseJSON[0], jqXHR.responseJSON[1]);
                    }
                    $("#rolePermissionLoader").addClass('hidden');
                }
            });
        });
    });
    function recursive_check_selected(node) {
        var selected_or_not = node.isSelected();
        selected_or_not ? node.select(false) : node.select(true);
        var children = node.getChildren();
        if (children != null) {
            for (var i = 0; i < children.length; i++) {
                recursive_check_selected(children[i]);
            }
        }
    }
    function buildRolePermissionsTree(permissions){
        $('#rolePermissionLoader').removeClass('hidden');
        $.ajax({
            url: "SettingsAjax/getRootRolesParents",
            data: {role_id:$('#Parent_ID').val(),parent_id:0,current_role_id:$('#Role_ID').val()},
            dataType: "JSON",
            complete: function (jqXHR, status) {
                if (status == 'success') {
                    var response = jqXHR.responseJSON,root_parents = response['parent'],
                        tab_content=response['tab_content'],ulContent = '';
                    for(i=0 ;i<root_parents.length;i++){
                        ulContent += '<li role="presentation" class="'+(i == 0 ? 'active' : '')+'"  ><a href="#tab'+(i+1)+'" aria-controls="home" role="tab" data-toggle="tab" aria-expanded="false">'+root_parents[i]['Permission_Text']+'</a></li>';
                    }
                    $('#DataTree ul').append($(ulContent));
                    $('#DataTree .tab-content').html(tab_content);
                    buildDynatreee(permissions);
                    $('#submit_role_permission').attr('disabled',false);
                    $('#rolePermissionLoader').addClass('hidden');
                }
            }
        });
    }
    function buildDynatreee(permissions){
        $(".tree").dynatree({
            checkbox: true,
            selectMode: 4,
            keyboard: false,
            minExpandLevel: 2,
            fx: {height: "toggle", duration: 200},
            autoFocus: false,
            onSelect: function (flag, node) {
                if (flag) {
                    var parent = node.getParent();
                    if (parent != null) {
                        node.getParent().select(true);
                    }
                } else if (!flag) {
                    var children = node.getChildren();
                    if (children != null) {
                        for (var i = 0; i < children.length; i++) {
                            children[i].select(false);
                        }
                    }
                }
            }
            //            ,
            //            onFocus:function(node){
            ////                node.select(true)
            //                var children = node.getChildren();
            //                if (children != null) {
            //                    for (var i = 0; i < children.length; i++) {
            //                        children[i].select(true);
            //                    }
            //                }
            //            }
        });
        if(permissions.length > 0){
            for (var i = 0; i < permissions.length; i++) {
                $(".tree").each(function () {
                    var tree = $(this).dynatree("getTree");
                    var node = tree.getNodeByKey(permissions[i]);
                    if (node != null) {
                        node.select(true);
                        return;
                    }
                });
            }
        }
    }

</script>