// JavaScript Document
$('.excelFile').live('click', function () {
    var btn = $(this);
    btn.attr('disabled', 'disabled');
    $('#ExcelStatus').html('جارى تصدير الملف...');
    var tblId = $(this).attr('data-tblId');
    var path = $(this).attr('data-path');
    var table = $('#' + tblId).html();
    var path2 = $('#' + path).html();
    $.post('exportexcel.php', {data: table, applyDefaultStyles: 1, path: path2}, function (data) {
        btn.removeAttr('disabled');
        $('#ExcelStatus').html(data);
    });
});
function copyToClipboard(text) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val(text).select();
    document.execCommand("copy");
    $temp.remove();
}

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;
        });
    });
}

jQuery.fn.forcepositiveNumCVA = 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)
                    ||
                    (e.ctrlKey && (key == 67 || key == 86 || key == 65)))//allow copy && paste && ctrl+a
                return true;

            return false;
        });
    });
}

jQuery.fn.forcepositivefloat = function () {

    return this.each(function () {
        $(this).keydown(function (e) {
            var presedval = e.key;
            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 ||
                    // pageup and pagedown
                    key == 33 || key == 34 ||
                    // left and right arrows
                    key == 37 || key == 39 ||
                    // Del and Ins
                    key == 46 || key == 45 ||
                    //dot or point  .  on keyboard  for one time
                            (key == 110 && $(this).val().indexOf(".") < 0) ||
                            (key == 190 && $(this).val().indexOf(".") < 0 && presedval == ".") ||
                            (e.ctrlKey && (key == 67 || key == 86 || key == 65)))//allow copy && paste && ctrl+a)
                return true;

            return false;
        });
    });
}

//: not accepted :(
jQuery.fn.forceMac = 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 ||
                    // A to F
                    key >= 65 && key <= 70 ||
                    // column , leftshift , right shift
                    key == 58 || key == 403 || key == 404 || key == 16 ||
                    //Backspace and Enter
                    key == 8 || key == 13 ||
                    (e.shiftKey && key == 58) || // allow  :
                    (e.ctrlKey && (key == 67 || key == 86 || key == 65)))//allow copy && paste && ctrl+a)
                return true;

            return false;
        });
    });
}
$(document).ready(function (e) {
    $(".positiveNo").forcepositiveNum();
    $(".positiveNoCVA").forcepositiveNumCVA();
    $(".positivefloat").forcepositivefloat();

    $('.delthis').live('click', function () {
        var go = $(this).attr('data-go');
        $('#delThisBtn').attr('data-go', go);
        $('#confirmThis').modal('show');
    });

    $('#delThisBtn').live('click', function () {
        var go = $(this).attr('data-go');
        window.location.href = go;

    });
    if ($('#cashStatus').val() == "1") {//need to be cashed
        $.post('dailyentryajax.php?do=cashheader', {mymenu: $('#mymenu').html()}, function (data) {
        });
    }
    /* ------------------------------------------------------------------------ */
    //fatmaaaaa
    var sui = $('#sui').val();
    //this means every 2 minutes check if 30minutes passed from lastTabOpenMoment =>check session
    var today = new Date();
    var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
    var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    var now = date + ' ' + time;
    localStorage.setItem('lastTabOpenTime' + sui, now);
    localStorage.setItem('lastTabOpenMoment' + sui, Date.now());//Date.now() is time in milliseconds
    if (Number($('#stopsessioncheck').val()) != 1) {
        ckSession();
    }
    function ckSession() {
        //console.log('in check');
        var reCallSetTimeOutTime = (2 * 60 * 1000);//this is 2 min //1000 millisecond in a second, 60 sec, 3 min
        var ckTimeInMillis = (30 * 60 * 1000);//this is 30 mins//1000 millisecond in a second, 60 sec, 3 min
        setTimeout(function () {
            var start = localStorage.getItem('lastTabOpenMoment' + sui);
            var diffInMillis = Date.now() - start;
            //if(diff >= 30min)
            if (diffInMillis >= ckTimeInMillis) {//this means every 2 minutes check if 30minutes passed from lastTabOpenMoment =>check session,mark db as logout if session expired
                localStorage.setItem('lastTabOpenMoment' + sui, Date.now());
                //console.log((diffInMillis / 1000 / 60));
                $.ajax({
                    type: 'POST',
                    url: 'dailyentryajax.php?do=cksession',
                    data: {sui: sui},
                    success: function (data) {
                        if (data == 1) {
                            ckSession();
                        } else if (data == -1) {
                            alert("Your session has Expired,you should login again");
                        }
                    }
                });
            } else {
                ckSession();
            }
        }, reCallSetTimeOutTime);
    }
    /* ------------------------------------------------------------------------ */
    $('#notice_link').live('click', function () {
        var clicks = $(this).attr('data-clicks');
        if (clicks == "0")
        {
            $(this).attr('data-clicks', '1');
            $('#notice_total').html(" ... جارى العد ...");
            $.post('dailyentryajax.php?do=getnoticecount', function (data) {
                data = Number(data);
                $('#notice_total').html(data);
            });
        } else
        {
            window.location.href = "noticesController.php";
        }
    });

    $('.copyLinkToClipboard').live('click', function () {
        /* Select the text field */
        var temp = $("<input>");
        $("body").append(temp);
        temp.val($(this).attr("data-link")).select();
        try {
            /* Copy the text inside the text field */
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
        } catch (err) {
            console.log('Oops, unable to copy');
        }
        temp.remove();
    });


});


function dataTableClass() {
//    if ($.fn.DataTable.isDataTable('.dataTableClass')) {
//        $('.dataTableClass').DataTable().destroy();
//    }
//    if ($.fn.DataTable.isDataTable('.dataTableClassNoPaging')) {
//        $('.dataTableClass').DataTable().destroy();
//    }

    //to set default sort column using its html class no matter its place => [$('th.catClass').index(),'asc']
    //
    $('.dataTableClass').dataTable({
        dom: 'Bfrtip',
        buttons: [//'csv', 'pdf'
            {
                extend: "print",
                className: "btn dark btn-outline",
                text: "طباعه<i class='fa fa-print'></i>",
                exportOptions: {
                    //columns: '.show-print'
                    columns: ':visible'//columns: ':visible(:not(.hidden-print))'
                },
                customize: function (win) {
//                    $(win.document.body)
//                            .css('font-size', '10pt')
//                            .prepend(
//                                    '<img src="http://datatables.net/media/images/logo-fade.png" style="position:absolute; top:0; left:0;z-index:-1;" />'
//                                    );
                    $(win.document.body).find('table')
                            //.addClass('compact')
                            .css('direction', 'rtl');
                }
            }, {
                extend: "copy",
                className: "btn red btn-outline",
                text: "نسخ",
                exportOptions: {
                    //columns: '.show-print'
                    columns: ':visible'
                }
            }, {
                extend: "excel",
                className: "btn yellow btn-outline ",
                text: "اكسل",
                exportOptions: {
                    //columns: '.show-print'
                    columns: ':visible'
                }
            }, {
                extend: "colvis",
                className: "btn dark btn-outline",
                text: "المكونات"
            }, {
                /*                extend: "print",
                 className: "btn dark btn-outline",
                 text: "pdf<i class='fa fa-print'></i>",
                 exportOptions: {
                 //columns: '.show-print'
                 columns: ':visible'//columns: ':visible(:not(.hidden-print))'
                 },
                 customize: function (win) {
                 //                    $(win.document.body)
                 //                            .css('font-size', '10pt')
                 //                            .prepend(
                 //                                    '<img src="http://datatables.net/media/images/logo-fade.png" style="position:absolute; top:0; left:0;z-index:-1;" />'
                 //                                    );
                 $(win.document.body).find('table')
                 //.addClass('compact')
                 .css('direction', 'rtl');// then save as pdf from popup
                 }*/
            }
        ],
        "bStateSave": true,
        "language": {
            "aria": {
                "sortAscending": ": Used to order Ascending",
                "sortDescending": ": Used to order Descending"
            },
            "emptyTable": "لا يوجد بيانات",
            "info": "عرض _START_ من _END_ الى _TOTAL_ عناصر",
            "infoEmpty": "لا يوجد بيانات",
            "infoFiltered": "(تنقيه _MAX_ من الاجمالى)",
            "lengthMenu": " _MENU_ عنصر",
            "search": "البحث:",
            "zeroRecords": "لا يوجد بيانات تشابه البحث"
        },
        responsive: !0,
        "columnDefs": [
//            {// set default column settings
//                "orderable": false,
//                "searchable": false,
//                "targets": [lstone],
//                "className": 'hide-print'
//            },
//            {// set default column settings
//                "orderable": false,
//                "searchable": false,
//                "targets": [belastone],
//                "className": 'hide-print'
//            },
//            {// set default column settings
//                "orderable": false,
//                "searchable": false,
//                "targets": [thrdone],
//                "className": 'hide-print'
//            },
            {targets: '_all', "className": 'show-print'}],
        order: [
            [0, "asc"]
        ],
//        "paging": false,
        lengthMenu: [
            [5, 10, 15, 20, -1],
            [5, 10, 15, 20, "All"]
        ],
        pageLength: 10,
        dom: "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>"
    });
    $('.dataTableClass td').css("height", "30px");
    $('.dataTableClassNoPaging').dataTable({
        dom: 'Bfrtip',
        buttons: [//'csv', 'pdf'
            {
                extend: "print",
                className: "btn dark btn-outline",
                text: "طباعه<i class='fa fa-print'></i>",
                exportOptions: {
                    //columns: '.show-print'
                    columns: ':visible'
                },
                customize: function (win) {
//                    $(win.document.body)
//                            .css('font-size', '10pt')
//                            .prepend(
//                                    '<img src="http://datatables.net/media/images/logo-fade.png" style="position:absolute; top:0; left:0;z-index:-1;" />'
//                                    );
                    $(win.document.body).find('table')
                            //.addClass('compact')
                            .css('direction', 'rtl');
                }
            }, {
                extend: "copy",
                className: "btn red btn-outline",
                text: "نسخ",
                exportOptions: {
                    //columns: '.show-print'
                    columns: ':visible'
                }
            }, {
                extend: "excel",
                className: "btn yellow btn-outline ",
                text: "اكسل",
                exportOptions: {
                    //columns: '.show-print'
                    columns: ':visible'
                }
            }, {
                extend: "colvis",
                className: "btn dark btn-outline",
                text: "المكونات"
            }
        ],
        "bStateSave": true,
        "language": {
            "aria": {
                "sortAscending": ": Used to order Ascending",
                "sortDescending": ": Used to order Descending"
            },
            "emptyTable": "لا يوجد بيانات",
            "info": "عرض _START_ من _END_ الى _TOTAL_ عناصر",
            "infoEmpty": "لا يوجد بيانات",
            "infoFiltered": "(تنقيه _MAX_ من الاجمالى)",
            "lengthMenu": " _MENU_ عنصر",
            "search": "البحث:",
            "zeroRecords": "لا يوجد بيانات تشابه البحث"
        },
        responsive: !0,
        "columnDefs": [
//            {// set default column settings
//                "orderable": false,
//                "searchable": false,
//                "targets": [lstone],
//                "className": 'hide-print'
//            },
//            {// set default column settings
//                "orderable": false,
//                "searchable": false,
//                "targets": [belastone],
//                "className": 'hide-print'
//            },
//            {// set default column settings
//                "orderable": false,
//                "searchable": false,
//                "targets": [thrdone],
//                "className": 'hide-print'
//            },
            {targets: '_all', "className": 'show-print'}],
        order: [
            [0, "asc"]
        ],
        "paging": false,
        dom: "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>"
    });
    $('.dataTableClassNoPaging td').css("height", "30px");
}
$(document).ready(function () {
    dataTableClass();
});
// ************************************************************************** //
function setCookie(key, value, expiry) {
    var expires = new Date();
    expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
    document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}

function getCookie(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
}

function eraseCookie(key) {
    //var keyValue = getCookie(key);
    //setCookie(key, keyValue, '-1');
    setCookie(key, "", '-1');
}
// ************************************************************************** //