// JavaScript Document
// forceNumeric() plug-in implementation
var formatResult;
jQuery.fn.forcepositiveNum = function () {

    return this.each(function () {
        $(this).keydown(function (e) {
            var key = e.which || e.keyCode;
            //alert(key);
            if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
                    // numbers
                    key >= 48 && key <= 57 ||
                    // Numeric keypad
                    key >= 96 && key <= 105 ||
                    // comma, period and minus, . on keypad
                    //key == 190 || key == 188 || key == 109 || key == 110 ||
                    // Backspace and Tab and Enter
                    key == 8 || key == 9 || key == 13 ||
                    // Home and End
                    key == 35 || key == 36 ||
                    // left and right arrows
                    key == 37 || key == 39 ||
                    // Del and Ins
                    key == 46 || key == 45)
                return true;
            return false;
        });
    });
}
$(document).keypress(function (e) {
    if (e.which == 13) {
        var noOfEntries = $('#noOfEntries').val();
        $('#DE_add' + noOfEntries).click();
        return false;
    }
});

//dropdown-toggle
$(document).ready(function (e) {
//alert(document.getElementById("searchvalue").value);
    formatResult = function (data) {
        return  data.text;
    }

    /*---add--------------------------------------------------------------------------------------------------------------------------*/
    $(".positiveNo").forcepositiveNum();
    $('#newHoleEntry').live('click', function () {
        var noOfEntries = $('#noOfEntries').val();
        noOfEntries++;
        $('#DEMany').append('<div style="clear:both"></div>' +
                '<button type="button" class="btn btn-primary" style="float: left;" id="DE_add' + noOfEntries + '">اضافة</button>' +
                '<table class="table" >' +
                '<thead>' +
                '<tr>' +
                '<th>#</th>' +
                '<th>اسم الحساب</th>' +
                '<th>مدين</th>' +
                '<th>دائن</th>' +
                '<th>ملاحظة</th>' +
                '<th>مركز التكلفة</th>' +
                '<th>حذف</th>' +
                '</tr>' +
                '</thead>' +
                '<tbody id="DE_Table' + noOfEntries + '">' +
                '</tbody>' +
                '<tr class="mytotal totalDiv' + noOfEntries + '">' +
                '<th>الاجمالى' +
                '<input type="hidden" id="selectedIds' + noOfEntries + '" name="selectedIds' + noOfEntries + '" value=""/>' +
                '<input type="hidden" id="itr' + noOfEntries + '" name="itr' + noOfEntries + '" value="0" />' +
                '</th>' +
                '<th></th>' +
                '<th id="totalValueFrom' + noOfEntries + '">0</th>' +
                '<th id="totalValueTo' + noOfEntries + '">0</th>' +
                '<th></th>' +
                '<th></th>' +
                '<th></th>' +
                '</tr>' +
                '</table>' +
                '<br/>' +
                '<input type="hidden" id="totalValueFrom_hidden' + noOfEntries + '" name="totalValueFrom_hidden' + noOfEntries + '" value="0"/>' +
                '<input type="hidden" id="totalValueTo_hidden' + noOfEntries + '" name="totalValueTo_hidden' + noOfEntries + '" value="0"/>');
        $('#DE_add' + noOfEntries).live('click', function () {
            var itr = $('#itr' + noOfEntries).val();
            itr++;
            $('#DE_Table' + noOfEntries).append('<tr class="clearit"><td class="rowNo" style="font-weight: bold">' + itr + '</td>' +
                    '<td> <input type="hidden"  id="E_parent' + noOfEntries + '-' + itr + '" name="E_parent' + noOfEntries + '-' + itr + '" data-itr="' + itr + '" data-DEno="' + noOfEntries + '" data-placeholder="اختر" class="dailyParent wdt100"/></td>' +
                    '<td> <input name="valueFrom' + noOfEntries + '-' + itr + '" type="text" id="valueFrom' + noOfEntries + '-' + itr + '" data-itr="' + itr + '" data-DEno="' + noOfEntries + '" class="form-control positiveNo valueFrom valueFrom' + noOfEntries + '" value="" placeholder="0"/></td>' +
                    '<td> <input name="valueTo' + noOfEntries + '-' + itr + '" type="text" id="valueTo' + noOfEntries + '-' + itr + '" data-itr="' + itr + '" data-DEno="' + noOfEntries + '" class="form-control positiveNo valueTo valueTo' + noOfEntries + '" value="" placeholder="0"/></td>' +
                    '<td> <textarea class="form-control" rows="2" id="comment' + noOfEntries + '-' + itr + '" name="comment' + noOfEntries + '-' + itr + '"></textarea></td>' +
                    '<td> <select id="costcenterid' + noOfEntries + '-' + itr + '" name="costcenterid' + noOfEntries + '-' + itr + '" data-placeholder="اختر" style="width:200px">' +
                    $('#costCenterDiv').html() +
                    '</select></td>' +
                    '<td> <a class="btn btn-default btn-lg removeicon removethis" data-itr="' + itr + '" data-DEno="' + noOfEntries + '" data-type="fromDiv" style="padding:11px" tabindex="0"></a></td></tr>');
            $("#costcenterid" + noOfEntries + '-' + itr).select2();
            $("#E_parent" + noOfEntries + '-' + itr).select2({
                width: "300px",
                placeholder: "اختر",
                minimumInputLength: document.getElementById("searchvalue").value,
                //minimumInputLength: 3,
                multiple: false,
                quietMillis: 100,
                ajax: {
                    url: "dailyentryajax.php?do=getaccountstreeexcept",
                    dataType: 'json',
                    data: function (term, page) {
                        return {
                            term: term, //search term
                            page_limit: 10, // page size
                            ids: $('#selectedIds' + noOfEntries).val(),
                            myid: $("#parentFrom" + noOfEntries + '-' + itr).val(),
                        };
                    },
                    results: function (data) {
                        return {results: data};
                    }
                },
                formatResult: formatResult,
                initSelection: function (element, callback) {
                    var item = element.val().split(':');
                    var data = {id: item[0], text: item[1]};
                    callback(data);
                }
            });

            $('#itr' + noOfEntries).val(itr);
            $(".positiveNo").forcepositiveNum();
            resetRowNo();
        });


        $('#DE_add' + noOfEntries).click();
        $('#noOfEntries').val(noOfEntries);

    });
    //start with row
    $('#newHoleEntry').click();


    $('.valueFrom').live('keyup', function () {
//$(this).parent().parent('tr').css('background-color', '#8cbdee');
        $(this).css('background-color', '#9be8ff');
        var myitr = $(this).attr('data-itr');
        var DEno = $(this).attr('data-DEno');

        $("#valueTo" + DEno + "-" + myitr).val("");
        $("#valueTo" + DEno + "-" + myitr).attr("placeholder", 0);
        $("#valueTo" + DEno + "-" + myitr).css('background-color', 'white');
        calcTotalFrom(DEno);
        calcTotalTo(DEno);
    });
    $('.valueTo').live('keyup', function () {
//$(this).parent().parent('tr').css('background-color', '#c3a1c3');
        $(this).css('background-color', '#9be8ff');
        var myitr = $(this).attr('data-itr');
        var DEno = $(this).attr('data-DEno');

        $("#valueFrom" + DEno + "-" + myitr).val("");
        $("#valueFrom" + DEno + "-" + myitr).attr("placeholder", 0);
        $("#valueFrom" + DEno + "-" + myitr).css('background-color', 'white');
        calcTotalFrom(DEno);
        calcTotalTo(DEno);
    });
    $('.dailyParent').live('change', function () {
        var myDEno = $(this).attr('data-DEno');
        var myitr = $(this).attr('data-itr');
        var lastitr = $("#itr" + myDEno).val();

        var lastParentVal = $("#E_parent" + myDEno + "-" + lastitr).val();
        if (lastParentVal == "" || lastParentVal == "undefined")
        {
//do nothing
        } else
        {
//start with row
            $('#DE_add' + myDEno).click();
        }
    });
    function calcTotalFrom(DEno) {
        var total = 0;
        $(".valueFrom" + DEno).each(function (index, element) {
            total += Number($(this).val());
        });
        $('#totalValueFrom' + DEno).html(total);
        $('#totalValueFrom_hidden' + DEno).val(total);
        return total;
    }
    function calcTotalTo(DEno) {
        var total = 0;
        $(".valueTo" + DEno).each(function (index, element) {
            total += Number($(this).val());
        });
        $('#totalValueTo' + DEno).html(total);
        $('#totalValueTo_hidden' + DEno).val(total);

        return total;
    }
    $('.removethis').live('click', function () {
        $(this).parent().parent().remove();
        resetRowNo();
    });
    function resetRowNo() {

        var rowNo = 1;
        $('.rowNo').each(function (index, element) {
            $(this).html(rowNo);
            rowNo++;
        });
    }
    function selectIsRequired(DEno)
    {
        var valid = true;
        $('.valueFrom' + DEno).each(function (index, element) {
            var myitr = $(this).attr('data-itr');
            var DEno = $(this).attr('data-DEno');
            var accountid = $("#E_parent" + DEno + "-" + myitr).val();
            if ((accountid == 0 || accountid == ""))
            {
                $('#s2id_E_parent' + DEno + "-" + myitr).css({"border-color": "red", "border-weight": "1px", "border-style": "solid"});
                valid = false;
            } else
            {
                $('#s2id_E_parent' + DEno + "-" + myitr).css({"border-color": "white", "border-weight": "1px", "border-style": "solid"});
            }
        });
        return valid;
    }
    function valueIsRequired(DEno)
    {
        var valid = true;
        $('.valueFrom' + DEno).each(function (index, element) {
            var myitr = $(this).attr('data-itr');
            var DEno = $(this).attr('data-DEno');
            var valFrom = $("#valueFrom" + DEno + "-" + myitr).val();
            var valTo = $("#valueTo" + DEno + "-" + myitr).val();
            if ((valFrom == 0 || valFrom == "") && (valTo == 0 || valTo == ""))
            {
//$(this).css({"border-color": "red","border-width":"3px","border-style":"solid"});
                $("#valueFrom" + DEno + "-" + myitr).css('background-color', 'yellow');
                $("#valueTo" + DEno + "-" + myitr).css('background-color', 'yellow');
                valid = false;
            } else
            {
//$(this).css('background-color', 'white');
//$(this).css({"border-color": "#ccc","border-width":"1px","border-style":"solid"});
            }
        });
        return valid;
    }
    function checkBranch()
    {
        if (Number($('#branchid_entry').val()) < 0)
        {
            alert('من فضلك اختر الفرع');
            return false;
        }
    }
    function checkDate()
    {
        if ($('#dDateTime').val() == "")
        {
            $('#dDateTime').css({"border-color": "red", "border-weight": "1px", "border-style": "solid"});
            return false;
        } else
        {
            $('#dDateTime').css({"border-color": "#ccc", "border-weight": "1px", "border-style": "solid"});
            return true;
        }
    }

    function checkOneToManyRelation(DEno)
    {
        var fromCount = 0;
        var toCount = 0;
        var fromIDS = "";
        var toIDS = "";
        $('.valueFrom' + DEno).each(function (index, element) {
            var myitr = $(this).attr('data-itr');
            var E_parent = $("#E_parent" + DEno + "-" + myitr).val();
            var valueFrom = $("#valueFrom" + DEno + "-" + myitr).val();
            var valueTo = $("#valueTo" + DEno + "-" + myitr).val();
            if ((valueFrom != 0 && valueFrom != ""))
            {
                if (fromIDS.indexOf(E_parent) == -1)
                {
                    fromCount++;
                    fromIDS += E_parent + ",";
                }
            }
            if ((valueTo != 0 && valueTo != ""))
            {
                if (toIDS.indexOf(E_parent) == -1)
                {
                    toCount++;
                    toIDS += E_parent + ",";
                }
            }
        });
        var valid = false;
        if (toCount == 1 && fromCount == 1)
        {
            valid = true;
        } else if (fromCount == 1 && toCount > 1)
        {
            valid = true;
        } else if (toCount == 1 && fromCount > 1)
        {
            valid = true;
        }
        return valid;
    }

    function delLastRowIfEmpty(DEno)
    {
        //var DEno = $('#noOfEntries').val();
        $(".valueFrom" + DEno).each(function (index, element) {
            var myitr = $("#itr" + DEno).val();
            if ($("#E_parent" + DEno + "-" + myitr).val() == "" && $("#valueFrom" + DEno + "-" + myitr).val() == "" && $("#valueTo" + DEno + "-" + myitr).val() == "")
            {
                $("#valueFrom" + DEno + "-" + myitr).parent().parent().remove();
            }
        });

    }

//submit
    $('#btnAdd_dailyEntry').live('click', function () {

        $branchValid = checkBranch();
        if ($branchValid == false)
        {
            return false;
        }

        $dateValid = checkDate();
        if ($dateValid == false)
        {
            return false;
        }

        var DEno = Number($('#noOfEntries').val());
        DEno = DEno + 1;
        for ($i = 1; $i < DEno; $i++)
        {
            delLastRowIfEmpty($i);
            $valid = selectIsRequired($i);
            if ($valid == false)
            {
                return false;
            }
            $validVal = valueIsRequired($i);
            if ($validVal == false)
            {
                return false;
            }
//            $valid = checkOneToManyRelation($i);
//            if ($valid == false)
//            {
//                alert('عفوا غير مسموح ان يكون عناصر مدين كثيرة و عناصر دائن كثيرة فى نفس الوقت');
//                return false;
//            }


            var TotalFrom = calcTotalFrom($i);
            var TotalTo = calcTotalTo($i);
            if (TotalFrom == TotalTo)
            {
                if (TotalFrom == 0)
                {
                    alert('عفوا لا يتم تسجيل عملية اجمالى مدين و دائن فيها صفر');
                    return false;
                } else
                {
                    $('.totalDiv' + $i).css({"border-color": "#ddd", "border-weight": "1px", "border-style": "solid"});
                }
            } else
            {
                $('.totalDiv' + $i).css({"border-color": "red", "border-weight": "2px", "border-style": "solid"});
                alert('عفوا اجمالى من لا يساوى اجمالى الى');
                return false;
            }

        }


        $.post('dailyentrymanyajax.php?do=add', $("#dailyEntry_Form").serialize(), function (data) {
            data = data.split(",");
            if (data[0] == "-1")
            {
                alert('عفوا لقد حدث خطأ.حاول مرة اخرى');
            } else
            {
                window.location = "dailyentrymany.php?do=print&id=" + data[1];
            }
        });
    });
    //submit
    $('.DEsubmit').live('click', function () {
        var id = $(this).attr("id");
        if (id == "DESerach")
        {
            $("#DEForm").attr("action", "dailyentrymany.php");
            $("#DEForm").submit();
        } else if (id == "DESerachPrint")
        {
            $("#DEForm").attr("action", "dailyentrymany.php?do=print");
            $("#DEForm").submit();
        }
    });
});
$(".dailyParent").live('change', function () {
    var DEno = $(this).attr('data-DEno');
    getselectedids(DEno);
});
function getselectedids(DEno)
{
    var ids = '';
    $('.dailyParent').each(function (index, element) {
        var myDEno = $(this).attr('data-DEno');
        if (myDEno == DEno) {
            var type = this.type, tag = this.tagName.toLowerCase();
            if (tag == 'input' && type == "hidden")
            {
                if (this.value != "")
                {
                    ids += this.value + ',';
                }
            }
        }
    });
    $('#selectedIds' + DEno).val(ids);
}
