
<style type="text/css">
    .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;
    }
    .CenterHAndV{
        width:100%;
        height:100%;
        text-align:center;
        font-size: 18px;
    }
    #PrimaryCats .fa-circle-o{
        color: #4c0870;
        position: absolute;
        right: 10px;
        top: 10px;
        cursor:pointer;
    }
    #PrimaryCats .mainPageLinks{
        display: block;
        height: 100%;
    }
    #PrimaryCats .CenterHAndV .MiddleIcon{
        font-size: 45px;
        display: block;
        margin: 30px 0;
    }
    #AddNewItemDiv,#RemoveAddedItemDiv,#AddNewItemElement,#EditItemDiv{
        border: 1px dashed rgba(0, 0, 0, 0.25);
        padding: 10px;
        -webkit-border-radius: 2px;
        -moz-border-radius: 2px;
        border-radius: 2px;
    }
    .errorInputText{
        border:1px solid rgba(255,0,0,0.3);
    }
    .input-group > input,.input-group > span{
        border-color:#d5d5d5 !important;
    }
    #EmptyTreeMsg,#EmptyTreeResults{
        border: 1px dashed rgb(58, 143, 200);
        padding: 12px;
        margin: 0 10%;
        display:none;
    }
    #COAModalTitle{
        margin: 0px 0 26px 0;
    }
    #COAModalTitle > table{
        width: 80%;
        font-size: 19px;
        text-align: center;
        margin: 0 auto;
    }
    #COAModalTitle .MiddleIcon{
        font-size: 30px;
    }
    #SearchCOAContainer{
        margin:25px;   
    }
    .portlet-refresh.text-black{
        opacity: 1;
        font-size: large;
    }
    .hideme{
        visibility:hidden;
    }
    .input-group-addon i{
        color:#000 !important;
    }
    span.dynatree-node{
        width:100%;
    }
    .job_ids .select2-search-choice-close{
        background-color: transparent !important;
    }
</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="row">
    <div class="pull-right " style="margin-bottom: 9px;">
        <label style="font-size: 18px;"><?php print CommonLanguage::getMessage('arabic'); ?></label>
        <input type="checkbox" data-init-plugin="switchery" id="Is_Arabic"  <?php echo $Language == 'ar' ? 'checked' : '' ?>/></div>
</div>
<div class="row" id="PrimaryCats">
    <?php
    //    require("xhr/ajaxCOA.php");
    $Icons = array("scale15", "garage12", "gold3", "wallet19", "business156", "cash12", "dollar149", "accounting1", "hands8");
    $x2 = 0;
    //    echo "<pre>";
    //    die(print_r($RET));
    //    echo "</pre>";
    for ($x = 0; $x < count($RET); $x++) {
        $CurItem = $RET[$x];
        if ($CurItem["Parent_ID"] == 0) {
            $AccountCode = "<div style='width:10px;left:auto' class='panel-heading top-left top-right'><div class='panel-controls'><ul><li><a class='portlet-refresh text-black'>{$CurItem["Account_Code"]}</a></li></ul></div></div>";
            echo("<div class='col-md-4 col-lg-3 col-xlg-2 '><div class='row'><div class='col-md-12 m-b-10'><div style='border-bottom: 2px solid #4c0870;' class=' panel no-margin'><div class='container-xs-height full-height'>{$AccountCode}<a href='#' class='mainPageLinks' data-category-id='{$CurItem["Account_ID"]}' data-toggle='modal' data-target='#ChartOfAccounts'><table class='CenterHAndV'><tr><td><i class='MiddleIcon flaticon-{$Icons[$x2]}'></i><span class='Account_Name '>{$CurItem["Account_Name"]}</span></td></tr><tr><td><span class='Account_Arabic_Name hideme'>{$CurItem["Account_Arabic_Name"]}</span></td></tr></table></a></div></div></div></div></div>");
            $x2++;
        }
    }
    ?>
    <div class='col-md-4 col-lg-3 col-xlg-2 '><div class='row'><div class='col-md-12 m-b-10'><div style='border-bottom: 2px solid #4c0870;' class=' panel no-margin'><div class='container-xs-height full-height'><a href='#' class='mainPageLinks' data-category-id='all' data-toggle='modal' data-target='#ChartOfAccounts'><table class='CenterHAndV'><tr><td><i class='MiddleIcon flaticon-accounting1'></i><span class='Account_Name'>View All</span></td></tr><tr><td><span class='Account_Arabic_Name hideme'>عرض الكل</span></td></tr></table></a></div></div></div></div></div>
</div>
<div class="modal  fade " data-backdrop="static" id="ChartOfAccounts" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" style="">
        <div class="modal-content">
            <div id="ModalDisabler" 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 class="modal-header clearfix text-left">
                <div id="account_alert"></div>
                <button type="button" class="close" data-dismiss="modal" id="CloseCOA" aria-hidden="true"><i class="pg-close fs-14"></i></button>
                <!--                <h5><span class="semi-bold"></span></h5>-->
                <div id="COAAlertUpdate"></div>
                <div id="COAModalTitle">
                    <table>
                        <tr>
                            <td style="width:40%"></td>
                            <td style="width:20%"></td>
                            <td style="width:40%"></td>
                        </tr>
                    </table>
                </div>
                <div id="SearchCOAContainer">
                    <div class="input-group transparent">
                        <span class="input-group-addon">
                            <i class="fa fa-search"></i>
                        </span>
                        <input id="SearchCOAInput" type="text" placeholder="<?php print CommonLanguage::getMessage('search'); ?>" class="form-control">
                    </div>
                </div>
            </div>
            <div class="modal-body">
                <div id="check-tree"></div>
                <div id="EmptyTreeMsg"><?php print CommonLanguage::getMessage('cat_empty_go_to'); ?><a href=""><?php print CommonLanguage::getMessage('accounts_library'); ?></a> <?php print CommonLanguage::getMessage('to_add_new_item'); ?></div>
                <div id="EmptyTreeResults"><?php print CommonLanguage::getMessage('no_match_item'); ?></div>
            </div>
            <div class="modal-footer">
                <div class="pull-right">
                    <button class="btn btn-complete" data-dismiss="modal" id="AddCOA"><?php print CommonLanguage::getMessage('Save'); ?></button>
                    <button class="btn btn-default" data-dismiss="modal" id="CloseCOA"  ><?php print CommonLanguage::getMessage('Close'); ?></button>
                </div>
            </div>
        </div>
    </div>
</div>



<div id="AddNewItemElement" class="hidden form-group"> 
    <div class="row"> 
        <div class="col-sm-1"> 
            <input id="generated_parent_code" type="text" readonly class="form-control" > 
        </div> 
        <div class="col-sm-1"> 
            <input id="generated_right_code" type="text"  class="form-control"> 
        </div> 
        <div class="col-sm-3"> 
            <input id="AddNewItemEnglishTitle" type="text" placeholder="Title" class="form-control"> 
        </div> 
        <div class="col-sm-3" style="display: flex;"> 
            <div class="cash_div">
                <input type="checkbox" class="ignore-dynatree-events" id="cash"/> 
                <label for="cash">Cash</label> 
            </div>
            <div class="cash_div">

                <input type="checkbox" class="ignore-dynatree-events" id="check"/> 
                <label for="check">Check</label> 
            </div>

            <div class="cash_div">

                <input type="checkbox" class="ignore-dynatree-events" id="credit"/> 
                <label for="credit">Credit Card</label> 
            </div>
            <div class="cust_div">

                <input type="checkbox" class="ignore-dynatree-events" id="cust"/> 
                <label for="cust">Parent Customer</label> 
            </div>
            <div class="supp_div">

                <input type="checkbox" class="ignore-dynatree-events" id="supp"/> 
                <label for="supp">Parent Supplier</label> 
            </div> 
        </div> 
        <div class="col-sm-3"> 
            <select class="full-width Currency_ID" name="Currency_ID" data-init-plugin="select2"> 
                <?php foreach ($currency_list as $currency): ?>
                    <option mysymbol="<?php echo $currency['Currency_Symbol']; ?>" <?php echo $local_currency == $currency['Currency_ID'] ? 'selected' : '' ?> value="<?php echo $currency['Currency_ID']; ?>"><?php echo $currency['Currency_Name'] . " - " . $currency['Currency_Code']; ?></option> 
                <?php endforeach; ?>
            </select> 
        </div> 
    </div> 
    <div class="job_div <?php echo smc_session()['default_setting']['activate_accounting_job'] != 1 ? 'hidden' : '' ?>">
        <div class="row ">
            <div class="col-md-6">
                <label><?php echo CommonLanguage::getMessage('jobs') ?></label>
            </div>

        </div>
        <div class="row ">
            <div class="col-md-6">
                <input type="hidden" class="job_ids full-width" name="job_ids" />
            </div>
            <div class="col-md-2">

                <input type="checkbox" class="ignore-dynatree-events job_obligatory" /> 
                <label for="job_obligatory">obligatory</label> 
            </div> 
            <div class="col-md-2 disable_div">

                <input type="checkbox" class="ignore-dynatree-events disable_account" /> 
                <label for="disable_account">disabled</label> 
            </div> 
        </div>
    </div>
    <div class="row" style="padding:5px 0 0 0;"> 
        <div class="col-sm-12" style="text-align:right"> 
            <button class="btn btn-xs btn-complete ButtonAdd" > <?php echo CommonLanguage::getMessage('Add') ?> </button> 
            <button class="btn btn-xs btn-default ButtonCancel"><?php echo CommonLanguage::getMessage('Close') ?></button> 
        </div> 
    </div> 
</div>


<script>
    var sure_to_delete = <?php echo json_encode(CommonLanguage::getMessage('sure_to_delete')); ?>,
            removeLang = <?php echo json_encode(CommonLanguage::getMessage('remove')); ?>,
            AddLang = <?php echo json_encode(CommonLanguage::getMessage('Add')); ?>,
            editLang = <?php echo json_encode(CommonLanguage::getMessage('Edit')); ?>,
            AccLang = <?php echo json_encode(CommonLanguage::getMessage('account_code')); ?>,
            Submitted_Successfully = <?php echo json_encode(CommonLanguage::getMessage('Submitted_Successfully')); ?>,
            Failed_Submit = <?php echo json_encode(CommonLanguage::getMessage('Failed_Submit')); ?>,
            sync_type = <?php echo json_encode(smc_session()['default_setting']['sync_type']); ?>,
            CancelLang = <?php echo json_encode(CommonLanguage::getMessage('Close')); ?>;
    var DoViewAllNodes = location.pathname.toString().match(/\/1$/) == null, ExpandAfterReloading = "", ItemColor = "#4c0870";
    var SearchTimeout;
    var IsArabic = false;
    var lang = <?php echo json_encode($Language) ?>;

    if (!DoViewAllNodes) {

        $("#EmptyTreeMsg > a").attr("href", location.pathname.toString().substr(0, location.pathname.toString().lastIndexOf("/")))
        $("#ChartOfAccounts .modal-footer").remove()
    } else {

        ItemColor = "#4c0870"
        $("#EmptyTreeMsg").remove()
    }
    $(".widget-8.panel").css("border-bottom-color", ItemColor);
    $("a[data-category-id]").css("color", ItemColor);
    $(function () {
        if (lang == 'ar') {
            IsArabic = true;
            $("#PrimaryCats span.Account_Arabic_Name ").removeClass("hideme")

        } else {
            IsArabic = false;
            $("#PrimaryCats span.Account_Arabic_Name ").addClass("hideme")
        }


        $("#Is_Arabic").on("change", function () {
            if ($(this).is(":checked")) {
                IsArabic = true;
                $("#PrimaryCats span.Account_Arabic_Name ").removeClass("hideme")

            } else {
                IsArabic = false;
                $("#PrimaryCats span.Account_Arabic_Name ").addClass("hideme")
            }

        })



        $("#check-tree").on("click", ".ButtonAdd", function () {
            $("#ModalDisabler").hide();
            var V1 = $("#AddNewItemEnglishTitle").removeClass("errorInputText"), V2 = $("#AddNewItemArabicTitle").removeClass("errorInputText"),
                    MyID = $(this).attr("MyID");
            if ($.trim(V1.val()) == "") {
                $("#AddNewItemEnglishTitle").addClass("errorInputText");
                return
            }
            if (!$("#generated_right_code").val().match(/^[0-9]*$/) || $("#generated_right_code").val() == "") {
                $("#generated_right_code").addClass("errorInputText");
                return
            }
            var acc_sub_type = [];
            if ($("#supp").is(":checked"))
                acc_sub_type.push('supp');
            if ($("#cust").is(":checked"))
                acc_sub_type.push('cust');
            if ($("#cash").is(":checked"))
                acc_sub_type.push('cash')
            if ($("#check").is(":checked"))
                acc_sub_type.push('check')
            if ($("#credit").is(":checked"))
                acc_sub_type.push('credit')
            //            console.log(acc_sub_type)
            //            return false;
            var myData = {
                Account_Name: $.trim(V1.val()),
                Account_Arabic_Name: $.trim(V2.val()),
                Parent_ID: MyID,
                Currency_ID: $(".Currency_ID option:selected").val(),
                Account_Code: $("#generated_parent_code").val() + $("#generated_right_code").val(),
                job_ids: $("input[name=job_ids]").val(),
                job_required: $("input.job_obligatory").is(":checked") ? 1 : 0,
                acc_sub_type: acc_sub_type
            }
            //if($.trim(V2.val()) == ""){$("#AddNewItemArabicTitle").addClass("errorInputText");return}
            $("#ModalDisabler").show();
            $.ajax({
                url: "xhr/ajaxCOA?cmd=addnewitem",
                method: "POST",
                encoding: "UTF-8",
                data: myData,
                complete: function (v, v2) {
                    $("#AddNewItemDiv").remove();
                    ExpandAfterReloading = MyID;
                    var Completed = function () {
                        if (ExpandAfterReloading != "") {
                            PageTreeObject.getNodeByKey(ExpandAfterReloading).expand()
                            ExpandAfterReloading = "";
                            $("#ModalDisabler").hide();
                        }
                    }
                    PageTreeObject.getNodeByKey(ExpandAfterReloading).appendAjax({
                        url: "xhr/ajaxCOA?" + (DoViewAllNodes ? "" : "status=1&") + "cmd=fetch&id=" + MyID,
                        debugLazyDelay: 750,
                        success: function () {
                            Completed();
                        },
                        error: function () {
                            Completed();
                        }
                    });
                }
            })

        })
        $("#check-tree").on("click", ".ButtonCancel", function () {
            $("#AddNewItemDiv").remove()
        })

        $("body").addClass("NoSearch")
        $(document).on("keydown", function (e) {
            if (e.which == 8 && e.target.tagName.toLowerCase() != "input") {
                return false
            }
            return true;
        })

        $("#check-tree").dynatree({
            title: "",
            checkbox: DoViewAllNodes,
            selectMode: 3,
            keyboard: false,
            fx: {height: "toggle", duration: 200},
            autoFocus: false,
            initAjax: {},
            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) {
                var RemoveButton = (!DoViewAllNodes && node.data.IsAdded == "1" && sync_type != 2 ? "<span onclick='RemoveNewItem(this)' class='AddButton fa fa-minus-circle ' style='margin:0'></span>" : "");
                return "<div class='TreeItem' MyAccNameArabic='" + node.data.Account_Arabic_Name + "' MyAccName='" + node.data.Account_Name + "' MyId='" + node.data.Account_ID + "' MyParent='" + node.data.Parent_ID + "' MyCode='" + node.data.Account_Code + "' MyCurrency='" + node.data.Currency_ID + "' data-is-pay='" + node.data.is_pay + "' data-is-cust='" + (node.data.is_cust) + "' data-is-supp='" + (node.data.is_supp) + "' main-type='" + node.data.main_type + "' sub-type='" + node.data.sub_type + "' data-jobs='" + node.data.job_ids + "' data-job-required='" + node.data.job_required + "' data-status ='" + node.data.Status_ID + "' data-is-parent='" + node.data.is_parent + "'><strong>" + node.data.Account_Code + "</strong> - " + node.data.Account_Name + (IsArabic ? " - " + node.data.Account_Arabic_Name : "") + (node.data.Currency_Symbol == null ? "" : " - " + node.data.Currency_Symbol) + (node.data.Status_ID == 0 ? ' <span class="red-star">(disabled)</span> ' : '') + (!DoViewAllNodes && sync_type != 2 ? (node.data.Status_ID == 1 ? "<span onclick='AddNewItem(this)' class='AddButton fa fa-plus-circle'></span>" : "") + (((node.data.main_type == 'sys' || node.data.main_type == 'pay') || (node.data.sub_type === 'main' && node.data.main_type === 'dep')) && sync_type != 2 ? "<span onclick='EditItem(this)' class='AddButton fa fa-pencil-square-o'></span>" : "") : "") + ((node.data.main_type == 'sys' || node.data.main_type == 'pay') ? 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) {
                node.appendAjax({
                    url: "xhr/ajaxCOA?" + (DoViewAllNodes ? "" : "status=1&") + "cmd=fetch&id=" + node.data.Account_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) {
                    /** sourceNode may be null for non-dynatree droppables.
                     *  Return false to disallow dropping on node. In this case
                     *  onDragOver and onDragLeave are not called.
                     *  Return 'over', 'before, or 'after' to force a hitMode.
                     *  Return ['before', 'after'] to restrict available hitModes.
                     *  Any other return value will calc the hitMode from the cursor position.
                     */
//console.log(node)
//console.log(sourceNode)
//                    var NodeType = parseInt(node.data.department_id),
//                            SourceNodeType = parseInt(sourceNode.data.department_id)
                    if ((node.data.Account_ID != sourceNode.data.Parent_ID))
                        return true;
                    else if (node.data.Account_ID == sourceNode.data.Parent_ID)
                        return false;
                },
                onDrop: function (node, sourceNode, hitMode, ui, draggable) {
                    var Data = {
                        parent_id: node.data.Account_ID,
                        parent_code: node.data.Account_Code,
                        account_id: sourceNode.data.Account_ID,
                        old_parent_id: sourceNode.data.Parent_ID,
                        current_code: sourceNode.data.Account_Code
                    }
//                    $("#ModalDisabler").show();
$("#account_alert").addClass("hidden")
                    $.ajax({
                        url: "xhr/update_acc_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.Account_ID;

                                    var Completed = function () {
                                        if (ExpandAfterReloading != "") {
                                            PageTreeObject.getNodeByKey(ExpandAfterReloading).expand()
                                            ExpandAfterReloading = "";
                                            $("#ModalDisabler").hide();
                                        }
                                    }
                                    PageTreeObject.getNodeByKey(ExpandAfterReloading).appendAjax({
                                        url: "xhr/ajaxCOA?" + (DoViewAllNodes ? "" : "status=1&") + "cmd=fetch&id=" + node.data.Account_ID,
                                        debugLazyDelay: 750,
                                        success: function () {
                                            Completed();
                                        },
                                        error: function () {
                                            Completed();
                                        }
                                    });

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

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


                }
            }

        });
        window.PageTreeObject = $("#check-tree").dynatree("getTree");
        $("[data-category-id]").on("click", function () {
            var CurID = $.trim($(this).attr("data-category-id"));
            $("#COAModalTitle table tr td").eq(0).html($(this).find(".Account_Name").text());
            $("#COAModalTitle table tr td").eq(1).empty().append($(this).find(".MiddleIcon").clone());
            $("#COAModalTitle table tr td").eq(2).html((IsArabic ? $(this).find(".Account_Arabic_Name").text() : ''));
            $("#ChartOfAccounts").attr("CurID", CurID)
            LoadThisCategory(CurID);
        });
        $("#AddCOA").click(function () {
            $("#ModalDisabler").show();
            var Data = {nodes: []};
            $("#check-tree .dynatree-node").each(function () {
                if ($(this).hasClass("dynatree-partsel") && !$(this).hasClass("dynatree-selected")) {
                    Data.nodes.push([$(">.TreeItem", this).attr("MyId"), 2, "WithoutChildren"])
                } else if ($(this).hasClass("dynatree-selected")) {
                    Data.nodes.push([$(">.TreeItem", this).attr("MyId"), 1, "WithChildren"])
                } else {
                    Data.nodes.push([$(">.TreeItem", this).attr("MyId"), 0, "WithChildren"])
                }
            })
            $.ajax({
                url: "xhr/ajaxCOA?cmd=updatestatus",
                method: "POST",
                data: Data,
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        if (v1.responseText == 'OK') {
                            $("#COAAlertUpdate").attr("class", "alert alert-success").html(Submitted_Successfully).show()
                            setTimeout(function () {
                                $("#COAAlertUpdate").hide();
                            }, 2000)

                        }
                    } else {
                        $("#COAAlertUpdate").attr("class", "alert alert-danger").html(Failed_Submit).show()

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

                }
            })
        });
    })
    function RemoveNewItem(who) {
        var Item = $(who).parents(".dynatree-node"), MyID = $(who).parent().attr("MyID")
        $("#account_alert").addClass("hidden")

        var ADDDIV = '<div id="RemoveAddedItemDiv">' +
                '    <div class="row">' +
                '        <div class="col-sm-6">' + sure_to_delete +
                '        </div>' +
                '    </div>' +
                '    <div class="row" style="padding:5px 0 0 0;">' +
                '        <div class="col-sm-12" style="text-align:right">' +
                '            <button class="btn btn-xs btn-complete ButtonRemove" MyParent="' + $(who).parent().attr("myparent") + '" MyID="' + MyID + '">' + removeLang + '</button>' +
                '            <button class="btn btn-xs btn-default ButtonCancel">' + CancelLang + '</button>' +
                '        </div>' +
                '    </div>' +
                '</div>'
        if (Item.length > 0) {
            $("#RemoveAddedItemDiv").remove();
            ADDDIV = $(ADDDIV);
            Item.append(ADDDIV)
            ADDDIV.find(".ButtonRemove").on("click", function () {
                $("#RemoveAddedItemDiv").remove();
                MyID = $(this).attr("MyID");
                $("#ModalDisabler").show();
                ExpandAfterReloading = $(this).attr("MyParent");
                $.ajax({
                    url: "xhr/ajaxCOA?cmd=removeaddeditem",
                    method: "POST",
                    data: {MyID: MyID},
                    complete: function (v1, v2) {
                        if (v2 == "success" && v1.responseText == 'OK') {
                            var Completed = function () {
                                if (ExpandAfterReloading != "") {
                                    PageTreeObject.getNodeByKey(ExpandAfterReloading).expand()
                                    ExpandAfterReloading = "";
                                    $("#ModalDisabler").hide();
                                }
                            }
                            PageTreeObject.getNodeByKey(ExpandAfterReloading).appendAjax({
                                url: "xhr/ajaxCOA?" + (DoViewAllNodes ? "" : "status=1&") + "cmd=fetch&id=" + MyID,
                                debugLazyDelay: 750,
                                success: function () {
                                    Completed();
                                },
                                error: function () {
                                    Completed();
                                }
                            });
                        } else {
                            $("#account_alert").attr("class", "alert alert-danger").html(v1.responseText)
                            $("#ModalDisabler").hide();
                        }
                    }
                })
            })
            ADDDIV.find(".ButtonCancel").on("click", function () {
                $("#RemoveAddedItemDiv").remove()
            })
        }
    }
    function AddNewItem(who) {
        var Item = $(who).parents(".dynatree-node");
        var my_node_id = $(who).parents('.TreeItem').attr("myid"),
                node_is_pay = $(who).parents('.TreeItem').attr("data-is-pay"),
                node_is_cust = $(who).parents('.TreeItem').attr("data-is-cust"),
                node_is_supp = $(who).parents('.TreeItem').attr("data-is-supp"),
                main_type = $(who).parents('.TreeItem').attr("main-type"),
                sub_type = $(who).parents('.TreeItem').attr("sub-type"),
                parent_code_str = '', right_code_str = '';
        checkIfNoTransactionsOccurs(my_node_id, function (data) {
            if (data == 0) {
                toastr.error('<?php echo CommonLanguage::getMessage('unable_add_child_account'); ?>')
                return;

            }
            $("#EditItemDiv").remove()
            $.ajax({
                url: 'ACCAjax/coa_generate_code',
                method: "GET",
                data: {parent_id: my_node_id},
                dataType: 'json',
                complete: function (v1, v2) {
                    if (v2 == 'success') {
                        //                    console.log(v1.responseJSON)
                        parent_code_str = v1.responseJSON['parent_code'];
                        right_code_str = v1.responseJSON['right_code'];

                        var ADDDIV = $("#AddNewItemElement").clone();
                        ADDDIV.attr("id", "AddNewItemDiv")
                        ADDDIV.find("#generated_parent_code").val(parent_code_str)
                        ADDDIV.find("#generated_right_code").val(right_code_str)
                        $(".select2-container", ADDDIV).empty().remove()

                        if (node_is_pay != 1) {
                            ADDDIV.find(".cash_div,.check_div,.credit_div").remove()
                            //                        ADDDIV.find("#check").remove()
                            //                        ADDDIV.find("#credit").remove()
                        }
                        if (node_is_cust != 1) {
                            ADDDIV.find(".cust_div").remove()
                        }
                        if (node_is_supp != 1) {
                            ADDDIV.find(".supp_div").remove()
                        }

                        ADDDIV.find(".ButtonAdd").attr("MyID", $(who).parent().attr("MyID"))
                        //                    build_select2($("#job_id"), "ACCAjax/JobSearch")
                        build_select2(ADDDIV.find("input[name=job_ids]"), "ACCAjax/JobSearch", 1)


                        ADDDIV.removeClass("hidden")
                        if (Item.length > 0) {
                            $("#AddNewItemDiv").remove();
                            //                        ADDDIV = $(ADDDIV);


                            Item.append(ADDDIV)
                            $("select[name=Currency_ID]").show().select2()

                            //                        $(".Currency_ID").select2()

                            $("div.select2-container > a").removeAttr('href')
                            $("div.select2-container > a").removeAttr('tabindex')
                            //                        $(".pay_types").select2()

                        }

                    }
                }
            })

        });



    }
    function EditItem(who) {
        $("#AddNewItemDiv").remove()
        var Item = $(who).parents(".dynatree-node"),
                MyID = $(who).parent().attr("MyID"),
                MyCode = $(who).parent().attr("mycode"),
                AccName = $(who).parent().attr('myaccname'),
                MyParent = $(who).parent().attr("myparent"),
                CurrencyID = $(who).parent().attr("mycurrency"),
                node_is_pay = $(who).parent().attr("data-is-pay"),
                node_is_cust = $(who).parent().attr("data-is-cust"),
                node_is_supp = $(who).parent().attr("data-is-supp"),
                main_type = $(who).parent().attr("main-type"),
                data_jobs = $(who).parent().attr("data-jobs"),
                data_job_required = $(who).parent().attr("data-job-required"),
                sub_type = $(who).parent().attr("sub-type"),
                sub_type_arr = sub_type.split(','),
                AccNameArabic = $(who).parent().attr('MyAccNameArabic'),
                is_parent = $(who).parent().attr('data-is-parent'),
                data_status = $(who).parent().attr('data-status');
//        console.log(sub_type_arr)
        //        if($.inArray('credit', sub_type_arr) !='-1')
        //            alert()
        var parent_code = $(".TreeItem[myid=" + $(who).closest(".TreeItem").attr("myparent") + "]").attr("mycode"),
                parent_right_code = MyCode.substring(parent_code.length)
//        console.log(is_parent)
        var ADDDIV = $("#AddNewItemElement").clone();
        $(".select2-container", ADDDIV).empty().remove()
        ADDDIV.attr("id", "EditItemDiv")
        ADDDIV.find("#generated_parent_code").val(parent_code)
        ADDDIV.find("#generated_right_code").val(parent_right_code)
        ADDDIV.find("#AddNewItemEnglishTitle").val(AccName)
        if (is_parent == 1)
            ADDDIV.find(".disable_div").addClass('hidden')
        else
            ADDDIV.find(".disable_div").removeClass('hidden')
        ADDDIV.find("input.disable_account").prop("checked", (data_status == 1 ? false : true))
        if (node_is_pay != 1) {
            ADDDIV.find(".cash_div,.check_div,.credit_div").remove()
        } else {
            ADDDIV.find("#cash").prop("checked", (($.inArray('cash', sub_type_arr) != '-1') ? true : false))
            ADDDIV.find("#check").prop("checked", (($.inArray('check', sub_type_arr) != '-1') ? true : false))
            ADDDIV.find("#credit").prop("checked", (($.inArray('credit', sub_type_arr) != '-1') ? true : false))
        }
        if (node_is_cust != 1) {
            ADDDIV.find(".cust_div").remove()
        } else {
            ADDDIV.find("#cust").prop("checked", (($.inArray('cust', sub_type_arr) != '-1') ? true : false))

        }
        if (node_is_supp != 1) {
            ADDDIV.find(".supp_div").remove()
        } else {
            ADDDIV.find("#supp").prop("checked", (($.inArray('supp', sub_type_arr) != '-1') ? true : false))

        }
        ADDDIV.find(".job_obligatory").prop("checked", (data_job_required == 1 ? true : false))
        ADDDIV.find(".ButtonAdd").removeClass("ButtonAdd").addClass("ButtonEdit").text(editLang)
        ADDDIV.find(".ButtonEdit").attr("MyParent", $(who).parent().attr("myparent"))
        ADDDIV.find(".ButtonEdit").attr("MyID", MyID)
        build_select2(ADDDIV.find("input[name=job_ids]"), "ACCAjax/JobSearch", 1)
        //        build_select2(ADDDIV.find("input[name=job_ids]"), "xhr/CommonSearch?col_id=job_id&col_name=job_name&table=tbl_accounting_jobs", 1)


        $.ajax({
            url: "ACCAjax/get_jobs_by_ids",
            method: "GET",
            data: {job_ids: data_jobs},
            dataType: 'json',
            complete: function (v, v2) {
                ADDDIV.find("input[name=job_ids]").data().select2.updateSelection(v.responseJSON)
            }
        })

        if (Item.length > 0) {
            $("#EditItemDiv").remove();

            //            ADDDIV = $(ADDDIV);

            Item.append(ADDDIV)

            $("select[name=Currency_ID]").val(CurrencyID).show().select2()
            $("div.select2-container > a").removeAttr('href')
            $("div.select2-container > a").removeAttr('tabindex')
            $(" #EditItemDiv").removeClass("hidden")

            ADDDIV.find(".ButtonEdit").on("click", function () {
                $("#ModalDisabler").hide();
                var acc_sub_type = [];
                if ($("#supp").is(":checked"))
                    acc_sub_type.push('supp');
                if ($("#cust").is(":checked"))
                    acc_sub_type.push('cust');
                if ($("#cash").is(":checked"))
                    acc_sub_type.push('cash')
                if ($("#check").is(":checked"))
                    acc_sub_type.push('check')
                if ($("#credit").is(":checked"))
                    acc_sub_type.push('credit')
                var Data = {
                    Account_Code: $("#generated_parent_code").val() + $("#generated_right_code").val(),
                    Account_Name: $("#AddNewItemEnglishTitle").val(),
                    Account_Arabic_Name: $("#AddItemArabicTitle").val() ? $("#AddItemArabicTitle").val() : AccNameArabic,
                    Currency_ID: $("select[name=Currency_ID]").val(),
                    Account_ID: MyID,
                    acc_sub_type: acc_sub_type,
                    main_type: main_type,
                    job_ids: $("input[name=job_ids]").val(),
                    job_required: $("input.job_obligatory").is(":checked") ? 1 : 0,
                    Status_ID: $("input.disable_account").is(":checked") ? 0 : 1,
                    sub_type: sub_type
                }
                if (!$("#generated_right_code").val().match(/^[0-9]*$/) || $("#generated_right_code").val() == "") {
                    $("#generated_right_code").addClass("errorInputText");
                    return
                }
                if ($("#EditItemEnglishTitle").val() == "") {
                    $("#EditItemEnglishTitle").addClass("errorInputText");
                    return
                }
                //                if ($("#EditItemAccountCode").val() == "") {
                //                    return
                //                }
                $("#ModalDisabler").show();
                var thisActiveNode = $("#check-tree").dynatree("getActiveNode").getParent()
                //                console.log(thisActiveNode)
                //                return
                $.ajax({
                    url: "xhr/ajaxCOA?cmd=edititem",
                    method: "POST",
                    encoding: "UTF-8",
                    data: Data,
                    complete: function (v, v2) {
                        if (v2 == "success" && v.responseText == "OK") {
                            $("#EditItemDiv").remove();
                            ExpandAfterReloading = MyID;
                            var Completed = function () {
                                if (ExpandAfterReloading !== "") {
                                    PageTreeObject.getNodeByKey(thisActiveNode.data.key).expand()
                                    ExpandAfterReloading = "";
                                    $("#ModalDisabler").hide();
                                }
                            }
                            PageTreeObject.getNodeByKey(thisActiveNode.data.key).appendAjax({
                                url: "xhr/ajaxCOA?" + (DoViewAllNodes ? "" : "status=1&") + "cmd=fetch&id=" + MyParent,
                                debugLazyDelay: 750,
                                success: function () {
                                    Completed();
                                },
                                error: function () {
                                    Completed();
                                }
                            });
                        }
                    }
                })
            })
            ADDDIV.find(".ButtonCancel").on("click", function () {
                $("#EditItemDiv").remove()
            })
        }
    }
    function checkIfNoTransactionsOccurs(Account_ID, callback) {
        var return_value;
        $.ajax({
            url: "ACCAjax/checkAccountTransactions",
            method: "GET",
            data: {Account_ID: Account_ID},
            dataType: 'json',
            complete: function (v, v2) {
                if (v2 == 'success') {
                    var response = v.responseJSON;
                    callback(response)
                }
            }
        });
    }



    $("#SearchCOAContainer input").on("keyup", function (e) {
        clearTimeout(SearchTimeout);
        var DELAY = 500;
        if ($.trim($(this).val()) == "") {
            LoadThisCategory($("#ChartOfAccounts").attr("CurID"))
            return;
        }
        if (e.which == 13)
            DELAY = 1;
        SearchTimeout = setTimeout(function () {
            $("#ModalDisabler").show();
            $("#SearchCOAInput").attr("disabled", true)
            $("#check-tree").css("visibility", "hidden");
            PageTreeObject.options.initAjax.url = "xhr/ajaxCOA?" + (DoViewAllNodes ? "" : "status=1&") + "cmd=search&id=" + $("#ChartOfAccounts").attr("CurID") + "&term=" + $("#SearchCOAContainer input").val()
            PageTreeObject.reload(function () {
                $("#ModalDisabler").hide();
                $("#SearchCOAInput").attr("disabled", false).focus()
                $("#check-tree").css("visibility", "visible");
                setTimeout(function () {
                    $("#EmptyTreeResults").css("display", PageTreeObject.count() == 0 ? "block" : "none")
                }, 100)
                PageTreeObject.getRoot().visit(function (node) {
                    node.expand(true);
                })

            })
        }, DELAY)

    })

    function LoadThisCategory(CurID) {
        $("#EmptyTreeResults").hide()
        $("#check-tree").css("visibility", "hidden");
        $("<div id='AjaxLoader' style='height:100px;text-align:center'><img src='img/demo/progress.svg' /></div>").insertAfter($("#check-tree"))
        PageTreeObject.options.initAjax.url = "xhr/ajaxCOA?" + (DoViewAllNodes ? "" : "status=1&") + "cmd=fetch&id=" + CurID
        PageTreeObject.reload(function () {
            setTimeout(function () {
                $("#AjaxLoader").remove();
                $("#check-tree").css("visibility", "visible");
                try {
                    if (PageTreeObject.count() == 0) {
                        $("#EmptyTreeMsg").show()
                    } else {
                        $("#EmptyTreeMsg").hide()
                    }
                } catch (err) {
                }
            }, 100)
        })
    }




    $("#ChartOfAccounts").on("shown.bs.modal", function () {
        $("#ChartOfAccounts").unbind("click.dismiss.bs.modal")
        $("#account_alert").addClass("hidden")
    })
    $("#CloseCOA,#CancelCOA").bind("click", function () {
        $("#ChartOfAccounts").modal("hide")
    })

</script>