<style>
    .TreeItem{
        display:inline-block;
        cursor:default();
    }
    .TreeItem > .AddButton{
        position:relative;
        top:1px;
        cursor:pointer;
        margin:0 5px;
         font-size:18px;
        -webkit-transition:opacity 0.2s linear;
        -moz-transition:opacity 0.2s linear;
        transition:opacity 0.2s linear;
    }
    .TreeItem:hover > .AddButton{
        opacity:1;
        color: #ed9421;
        visibility:visible;
    }
    .dynatree-exp-cd span.dynatree-expander,.dynatree-exp-cdl span.dynatree-expander {
        background-position: 0 !important ;
        margin-top:-4px;
    }
</style>
<script src=" <?php echo THEME_PATH; ?>/plugins/jquery-ui/jquery-ui.min.js" type="text/javascript"></script>
<script src="<?php echo THEME_PATH; ?>/plugins/jquery-dynatree/jquery.dynatree.min.js" type="text/javascript"></script>
<link href="<?php echo THEME_PATH; ?>/plugins/jquery-dynatree/skin/ui.dynatree.css" rel="stylesheet" type="text/css" media="screen"/>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div id="activity_alert"></div>
            <div class="panel-title"> <?php print $title; ?></div>
            <div class="clearfix"></div>
        </div>
        <div class="panel-body">
            <?php if ($permissions->hasPermission('add_activity_tree')) { ?>
                <div class="row">
                    <div class="col-md-1">
                        <button class="btn btn-complete full-width" id="add_activity_tree"><?php echo CommonLanguage::getMessage('add') ?></button>
                    </div>
                </div>
            <?php } ?>
            <div class="row">
                <div id="check-tree"></div>
            </div>
            <div id="activity_disabler" style="position:absolute;left:0;right:0;top:0px;height:100%;background:rgba(255,255,255,0.9);z-index:999;display:none"><img class="image-responsive-height demo-mw-50" src="img/demo/progress.svg" alt="Progress" style="position: absolute;left: 50%;top: 50%;margin: -25px 0 0 -25px;" /></div>

        </div>
    </div>
</div>

<div class="modal fade" id="activity_tree_modal" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="add-label bold hidden h-labels"><?php echo CommonLanguage::getMessage('add_activity_tree'); ?></h5>
                <h5 class="edit-label bold hidden h-labels"><?php echo CommonLanguage::getMessage('edit_activity_tree'); ?></h5>
            </div>
            <div class="modal-body">
                <form id="activity_tree_form" method="POST" onsubmit="return false">
                    <input type='hidden' name='activity_id' id='activity_id'/>
                    <input type='hidden' name='parent_id' id='parent_id'/>
                    <div class="row">
                        <?php echo Forms::AlertDiv('activity_tree_alert'); ?>
                    </div>
                    <div class="row form-group">
                        <div class="col-md-12">
                            <label><?php echo CommonLanguage::getMessage('Code'); ?></label> 
                            <span class="red-star">*</span>
                            <input type="text"  id="activity_code" name="activity_code" class="form-control " required>
                        </div>
                    </div>  
                    <div class="row form-group">
                        <div class="col-md-12">
                            <label><?php echo CommonLanguage::getMessage('title'); ?></label> 
                            <span class="red-star">*</span>
                            <input type="text"  id="activity_title" name="activity_title" class="form-control " required>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-md-12">
                            <label><?php echo CommonLanguage::getMessage('alias'); ?></label> 
                            <input type="text"  id="activity_title_alias" name="activity_title_alias" class="form-control " >
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-md-12 ">
                            <input type="checkbox"  id="is_final" name="isfinal">
                            <label><?php echo CommonLanguage::getMessage('is_final'); ?></label> 
                        </div>
                    </div>
                    <div class="row form-group account_div">
                        <div class="col-md-12">
                            <label><?php echo CommonLanguage::getMessage('account'); ?></label> 
                            <span class="red-star">*</span>
                            <input type="hidden"  id="account_id" name="account_id" class="full-width">
                        </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 btn-complete" id="submit_activity_tree"><?php print CommonLanguage::getMessage('Save'); ?></button>
            </div>
            <?php echo Forms::ModalLoader('activity_tree_loader'); ?>
        </div>
    </div>
</div>
<script>
    var ExpandAfterReloading = "",
            add_activity_tree_perm = <?php echo json_encode($permissions->hasPermission('add_activity_tree')); ?>,
            edit_activity_tree_perm = <?php echo json_encode($permissions->hasPermission('edit_activity_tree')); ?>;
    delete_activity_tree_perm = <?php echo json_encode($permissions->hasPermission('delete_activity_tree')); ?>;
    $(function () {
        $('#is_final').on('click', function () {
            if ($(this).is(":checked")) {
                $('.account_div').removeClass('hidden');
                $('#account_id').attr('required', true);
            } else {
                $('.account_div').addClass('hidden');
                $('#account_id').attr('required', false);
                $('#account_id').val('').attr('data-select-name', '').trigger('change');
            }
        });
        build_select2($("#account_id"), "xhr/accIDSearch");
        $("#check-tree").dynatree({
            title: "",
            checkbox: false,
            selectMode: 3,
            keyboard: false,
            fx: {height: "toggle", duration: 200},
            autoFocus: false,
            initAjax: {
                url: "ACCAjax/get_activity_tree?cmd=fetch&id=0",
            },
            onPostInit: function (isReloading, isError) {
            },
            onActivate: function (node) {
            },
            onCreate: function (dtnode, nodeSpan) {
                if (dtnode.data.DontShow == "yes")
                    dtnode.li.style.display = "none";
            },
            onCustomRender: function (node) {
                return "<div class='TreeItem " + (node.data.is_final == 1 ? 'red-star' : '') + "'   data-id='" + node.data.activity_id + "' data-parent-id='" + node.data.parent_id + "'  data-name='" + node.data.activity_title + "' data-alias-name = '"+node.data.activity_title_alias+"' data-account-name='" + node.data.Account_Name + "'data-account-id='" + node.data.account_id + "' data-is-final='" + node.data.is_final + "' data-code='" + node.data.activity_code + "'><strong>" + node.data.activity_code + "</strong> - " + node.data.activity_title +(node.data.activity_title_alias ? (' - '+node.data.activity_title_alias) : '')+ ((add_activity_tree_perm && node.data.is_final == 0) ?
                        "<span onclick='AddNewItem(this)' data-id = '" + node.data.activity_id + "' class='AddButton fa fa-plus-circle'></span>" : "") + (edit_activity_tree_perm ? "<span onclick='EditItem(this)' class='AddButton fa fa-pencil-square-o'></span>" : "") + (delete_activity_tree_perm ? "<span onclick='RemoveNewItem(this)' data-id = '" + node.data.activity_id + "' class='AddButton fa fa-minus-circle' style='margin:0'></span>" : "") + "</div>";
            },
            onRender: function (node, nodeSpan) {
                //                if (node.data.Account_Status == 1) {
                //                    node.select()
                //                    $(nodeSpan).find(".TreeItem").addClass("OriginallyChecked")
                //                } else {
                //                    if (node.data.Account_Status == 2) {
                //                        setTimeout(function () {
                //                            $(nodeSpan).addClass("dynatree-partsel")
                //                        }, 100)
                //                    } else {
                //                        $(nodeSpan).find(".TreeItem").addClass("OriginallyUnChecked")
                //                    }
                //                }
            },
            onLazyRead: function (node) {
                node.appendAjax({
                    url: "ACCAjax/get_activity_tree?cmd=fetch&id=" + node.data.activity_id,
                    debugLazyDelay: 750
                });
            },
            dnd: {
                onDragStart: function (node) {
                    /** This function MUST be defined to enable dragging for the tree.
                     *  Return false to cancel dragging of node.
                     */
                    logMsg("tree.onDragStart(%o)", node);
                    return true;
                },
                onDragStop: function (node) {
                    // This function is optional.
                    logMsg("tree.onDragStop(%o)", node);
                },
                autoExpandMS: 1000,
                preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
                onDragEnter: function (node, sourceNode) {
                    if ((node.data.activity_id != sourceNode.data.parent_id))
                        return true;
                    else if (node.data.activity_id == sourceNode.data.parent_id)
                        return false;
                },
                onDrop: function (node, sourceNode, hitMode, ui, draggable) {
                    var Data = {
                        parent_id: node.data.activity_id,
                        activity_id: sourceNode.data.activity_id,
                    }
//                    console.log(Data)
////                    $("#activity_disabler").show();
                    $("#activity_alert").addClass("hidden")
                    $.ajax({
                        url: "ACCAjax/update_activity_node",
                        data: Data,
                        method: "POST",
                        complete: function (jqXHR, status) {
                            if (status == 'success') {
                                if (jqXHR.responseText == "OK") {
//                                sourceNode.data.Account_Code = '888'
                                    sourceNode.move(node, hitMode);
                                    ExpandAfterReloading = node.data.activity_id;

                                    var Completed = function () {
                                        if (ExpandAfterReloading != "") {
                                            PageTreeObject.getNodeByKey(ExpandAfterReloading).expand()
                                            ExpandAfterReloading = "";
                                            $("#activity_disabler").hide();
                                        }
                                    }
                                    PageTreeObject.getNodeByKey(ExpandAfterReloading).appendAjax({
                                        url: "ACCAjax/get_activity_tree?cmd=fetch&id=" + node.data.activity_id,
                                        debugLazyDelay: 750,
                                        success: function () {
                                            Completed();
                                        },
                                        error: function () {
                                            Completed();
                                        }
                                    });

                                } else {
                                    $("#activity_alert").attr("class", "alert alert-danger").html(jqXHR.responseText)
                                }
                            }

                            $("#activity_disabler").hide();
                        }
                    })
//                    sourceNode.move(node, hitMode);
//                    updateParentForDepartment(sourceNode.data.department_id, sourceNode.parent.data.department_id)


                }
            }
        });
        window.PageTreeObject = $("#check-tree").dynatree("getTree");
        $("#add_activity_tree").on("click", function () {
            AddNewItem();
        });
        $("#submit_activity_tree").on("click", function () {
            if (!$("#activity_tree_form").valid())
                return;
            $("#activity_tree_loader").removeClass('hidden');
            var Data = new FormData(document.getElementById("activity_tree_form"));
            Data.append('is_final', $('#is_final').is(":checked") ? 1 : 0);
            $.ajax({
                url: "ACCAjax/submit_activity_tree",
                method: "POST",
                data: Data,
                processData: false,
                contentType: false,
                dataType: "JSON",
                complete: function (jqXHR, status) {
                    if (status == 'success') {
                        if (jqXHR.responseJSON[1] == "success") {
                            if ($("#parent_id").val() == 0) {
                                window.PageTreeObject.reload();
                            } else {
                                refresh_node($("#parent_id").val());
                            }
                            hideModalAlert('activity_tree_modal', 'activity_tree_alert');
                        }
                        AddAlert("#activity_tree_alert", jqXHR.responseJSON[0], jqXHR.responseJSON[1]);
                    }
                    $("#activity_tree_loader").addClass('hidden');
                }
            });
        });
    });
    function AddNewItem(node) {
        var parent_id = node == undefined ? 0 : $(node).attr("data-id");
        $("#parent_id").val(parent_id);
        $("#is_final").prop('checked', false);
        $("#activity_id").val(0);
        $('#activity_tree_modal .add-label').removeClass('hidden');
        $('.account_div').addClass('hidden');
        $('#account_id').attr('required', false);
        $("#activity_tree_modal").modal("show");
    }
    function RemoveNewItem(div) {
        var activity_id = $(div).attr('data-id');
        IncludeDeleteModal(common_delete_modal, {entry_value: activity_id}, function () {
            $(div).closest('li').remove();
        }, "ACCAjax/delete_activity_tree");
    }
    function refresh_node(node_id) {
        ExpandAfterReloading = node_id;
        var Completed = function () {
            if (ExpandAfterReloading != "") {
                PageTreeObject.getNodeByKey(ExpandAfterReloading).expand()
                ExpandAfterReloading = "";
                $("#activity_disabler").hide();
            }
        }
        PageTreeObject.getNodeByKey(ExpandAfterReloading).appendAjax({
            url: "ACCAjax/get_activity_tree?cmd=fetch&id=" + node_id,
            debugLazyDelay: 750,
            success: function () {
                Completed();
            },
            error: function () {
                Completed();
            }
        });
    }
    function EditItem(node) {
        var current_name = $(node).parent().attr("data-name"),
             current_alias_name = $(node).parent().attr("data-alias-name"),
                current_id = $(node).parent().attr("data-id"),
                account_id = $(node).parent().attr("data-account-id"),
                account_name = $(node).parent().attr("data-account-name"),
                current_code = $(node).parent().attr("data-code"),
                is_final = $(node).parent().attr("data-is-final");
        $('#activity_tree_modal .edit-label').removeClass('hidden');
        $("#activity_id").val(current_id);
        if (account_id != 'null')
            $("#account_id").val(account_id).attr('data-select-name', account_name).trigger('change');
        $("#activity_title").val(current_name);
        $("#activity_title_alias").val(current_alias_name);
        $("#activity_code").val(current_code);
        $("#is_final").prop('checked', is_final == 0 ? false : true);
        if (is_final == 1) {
            $('.account_div').removeClass('hidden');
            $('#account_id').attr('required', true);
        } else {
            $('.account_div').addClass('hidden');
            $('#account_id').attr('required', false);
            $('#account_id').val('').attr('data-select-name', '').trigger('change');
        }
        $("#activity_tree_modal").modal("show")
    }
</script>
