<style>
    .table thead tr >th{
        background-color: #4c0870;
        color:#fff;
    }
    .table thead tr th[class*='sorting_'] {
        color: #FFFFFF;
    }
    .bg-master-lighter {
        border:none;
        background-color:#fff;
        border-top:1px solid #ddd; 
    }
    .btn-default{
        border: none;
        background-color: #eee;
    }
    .btn-default:hover{
        background-color:#ed9421 !important;
        color:#fff;
        border: none;
    }
    .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;
        visibility:visible;
        color: #ed9421;
    }
    .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 class="panel-title"> <?php print CommonLanguage::getMessage('projects'); ?></div>
            <div class="clearfix"></div>
        </div>
        <div class="panel-body">
            <?php if ($permissions->hasPermission('add_project')) { ?>
            <div class="row">
                <div class="col-md-1">
                    <button class="btn btn-complete full-width" id="add_new_project" data-target="#add_projects" data-toggle="modal"><?php echo CommonLanguage::getMessage('add') ?></button>
                </div>
            </div>
            <?php } ?>
            <div class="row">
                <div id="check-tree"></div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade " data-backdrop="static" id="add_projects" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm" >
        <div class="modal-content">
            <div class="modal-header clearfix text-left">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"><i class="pg-close fa-22"></i></span></button>
                <h4 class="modal-title"><?php print CommonLanguage::getMessage('projects') ?></h4>
                <div id="assignProjectAlert"></div>
            </div>
            <div class="modal-body">
                <form id="AssignProjectForm">
                    <div class="row">
                        <div class=" col-md-6 m-t-10 " >
                            <label class="labelText"><?php print CommonLanguage::getMessage('parent_code'); ?><span class="red-star">*</span></label>
                            <input type="text" class="form-control" disabled id="parent_code" name="parent_code" required/>
                        </div>
                        <div class=" col-md-6 m-t-10 " >
                            <label class="labelText"><?php print CommonLanguage::getMessage('right_code'); ?><span class="red-star">*</span></label>
                            <input type="text" class="form-control" id="right_code" name="right_code" required/>
                        </div>
                        <div class=" col-md-12 m-t-10 " >
                            <label class="labelText"><?php print CommonLanguage::getMessage('Name'); ?><span class="red-star">*</span></label>
                            <input type="text" class="form-control" id="project_name" name="project_name" required/>
                        </div>
                    </div>
                </form>
            </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 bg-complete white" id="assignBtn" style="width:auto"><?php print CommonLanguage::getMessage('Save') ?></button>
            </div>
        </div>
    </div>
</div>
<script>
    var title = <?php echo json_encode(CommonLanguage::getMessage('projects')); ?>,
        Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Required_Fields = <?php echo json_encode(CommonLanguage::getMessage('Required_Fields')); ?>,
                Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>;
                var IsEdit = false, IDToEdit = 0;
    var DoViewAllNodes = location.pathname.toString().match(/\/1$/) == null, ExpandAfterReloading = "";
    $(function () {
        $("#check-tree").dynatree({
            title: "",
            checkbox: false,
            selectMode: 3,
            keyboard: false,
            fx: {height: "toggle", duration: 200},
            autoFocus: false,
            initAjax: {
                url: "ACCAjax/get_project_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";
                //                console.log(dtnode)
            },
            onCustomRender: function (node) {
                //                console.log(node.data)
                var RemoveButton = (!DoViewAllNodes ? "<span onclick='RemoveNewItem(this)' class='AddButton fa fa-minus-circle hidden' style='margin:0'></span>" : "");
                return "<div class='TreeItem'   MyId='" + node.data.project_id + "' MyParent='" + node.data.parent_id + "' MyCode='" + node.data.project_code + "' MyName='" + node.data.project_name + "'><strong>" + node.data.project_code + "</strong> - " + node.data.project_name +
                    "<span onclick='AddNewItem(this)' data-code='" + node.data.project_code + "' data-id = '" + node.data.project_id + "' class='AddButton fa fa-plus-circle'></span><span onclick='EditItem(this)' class='AddButton fa fa-pencil-square-o'></span>"  + (RemoveButton ) + "</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) {
                //                console.log(node)
                node.appendAjax({
                    url: "ACCAjax/get_project_tree?cmd=fetch&id=" + node.data.project_id,
                    debugLazyDelay: 750
                });
            }
        });
        window.PageTreeObject = $("#check-tree").dynatree("getTree");
        $("#add_new_project").on("click", function () {
            IsEdit = false;
            IDToEdit = 0;
            $("#add_projects").attr("data-parent", 0)
            AddNewItem()
        })
        //
        //        RebuildDataTable(title, [0], "ACCAjax/projects_list")
        //
        $("#assignBtn").on("click", function () {
            $("#assignProjectAlert").removeClass('hidden')
            if ($("#project_name").val() == '') {
                $("#assignProjectAlert").attr("class", "alert alert-danger").html(Required_Fields)
                return false;
            }
            var DataArr = new FormData(document.getElementById("AssignProjectForm"));
            DataArr.append("project_id", IDToEdit)
            DataArr.append("project_code", ($("#parent_code").val() + $("#right_code").val()))
            DataArr.append("parent_id", ($("#add_projects").attr("data-parent") || 0))
            DataArr.append("is_edit", (IsEdit ? 1 : 0))
            $.ajax({
                url: "ACCAjax/add_edit_projects",
                method: "POST",
                dataType: 'json',
                data: DataArr,
                processData: false,
                contentType: false,
                complete: function (v1, v2) {
                    if (v2 == "success" && v1.responseJSON == 'OK') {
                        $("#assignProjectAlert").attr("class", "alert alert-success").html(Submitted_Successfully)
                        //                        RebuildDataTable(title, [0], "ACCAjax/projects_list")
                        if ($("#add_projects").attr("data-parent") == 0) {
                            window.PageTreeObject.reload()
                            //                            $("#check-tree").dynatree("getTree")
                        } else {
                            refresh_node($("#add_projects").attr("data-parent"))
                        }
                        setTimeout(function () {
                            $("#assignProjectAlert").addClass('hidden')
                            $("#add_projects").modal("hide")
                        }, 1000)
                    } else {
                        $("#assignProjectAlert").attr("class", "alert alert-danger").html(v1.responseJSON)
                    }
                }
            })
        })
        //
        //        $("#tableWithSearch tbody").on('click', '.Edit', function () {
        //            IsEdit = true;
        //            IDToEdit = $(this).attr('data-id');
        //
        //            $("#project_name").val($(this).parents("tr").find("td:eq(0)").text())
        //            $("#add_projects").modal("show")
        //
        //        })
    })
    function AddNewItem(node) {
    
        //    console.log('here')get_next_project_code
        //        console.log($(node).attr("data-id"))
        //            console.log($("#add_projects").at/tr("data-parent")+'=========')
        var parent_id = node == undefined ? 0 : $(node).attr("data-id");
        checkIfNoTransactionsOccurs(parent_id,function(data){
            if(data == 0){
                toastr.error('<?php echo CommonLanguage::getMessage('unable_add_child_project');?>')
                return;
            }
            $.ajax({
                url: "ACCAjax/get_next_project_code",
                method: "GET",
                data: {parent_id: parent_id},
                complete: function (v1, v2) {
                    console.log(v1.responseText)
                    var parent_code = node == undefined ? '' : $(node).attr("data-code"),
                        right_code = v1.responseText.substring(parent_code.length);
                    $("#parent_code").val(parent_code)
                    $("#right_code").val(right_code)
                    $("#add_projects").attr("data-parent", parent_id)
                    $("#add_projects").modal("show")
                }
            })
        })
    }
    function refresh_node(node_id) {
        ExpandAfterReloading = node_id;
        var Completed = function () {
            if (ExpandAfterReloading != "") {
                PageTreeObject.getNodeByKey(ExpandAfterReloading).expand()
                ExpandAfterReloading = "";
                $("#ModalDisabler").hide();
            }
        }
        PageTreeObject.getNodeByKey(ExpandAfterReloading).appendAjax({
            url: "ACCAjax/get_project_tree?cmd=fetch&id=" + node_id,
            debugLazyDelay: 750,
            success: function () {
                Completed();
            },
            error: function () {
                Completed();
            }
        });
    }
    function EditItem(node) {
        var current_code = $(node).parent().attr("mycode"),
            current_name = $(node).parent().attr("myname"),
            current_id = $(node).parent().attr("myid"),
            parent_id = $(node).parent().attr("myparent"),
            parent_code = $(".TreeItem[myid=" + parent_id + "]").attr("mycode"),
            right_code = parent_code == undefined ? current_code : current_code.substring(parent_code.length);
        //        console.log("parent code=="+right_code)
        IsEdit = true;
        IDToEdit = current_id;
        $("#parent_code").val(parent_code)
        $("#right_code").val(right_code)
        $("#project_name").val(current_name)
        $("#add_projects").attr("data-parent", parent_id)
        $("#add_projects").modal("show")
    }
    function checkIfNoTransactionsOccurs(project_id,callback){
        var return_value;
        $.ajax({
            url: "ACCAjax/checkProjectTransactions",
            method: "GET",
            data: {project_id: project_id},
            dataType: 'json',
            complete: function (v, v2) {
                if(v2 == 'success'){
                    var response = v.responseJSON;
                    callback(response)
                }
            }
        });
    }
</script>
