$(document).on('click', '.Execute', function () {
    var this_btn = $(this);
    if (!this_btn.hasClass('processing...')) {
        this_btn.addClass('processing...');
        var type = this_btn.data('type');
        var from = $('#OS_' + type + '_From').val();
        var afterFromId = 0;
        var to = $('#OS_' + type + '_To').val();
        var tillEnd = 0;
        if ($('#OS_' + type + '_TillEnd').is(':checked')) {
            tillEnd = 1;
        }
        if (from != "" && (to != "" || tillEnd == true)) {
            //validations
            if (tillEnd == false) {
                if (Number(to) <= Number(from) || Number(to) == 0) {
                    alert('يجب ان يكون الى اكبر من من');
                    this_btn.removeClass('processing...');
                    return false;
                }
            }

            $('#OS_' + type + '_Loading').show();
            $('#OS_' + type + '_IdSpan').html("");
            $('#OS_' + type + '_Label').show();


            var url = '';
            switch (type) {
                case 'Product':
                    url = 'onlinestoresync.php?do=updateonlineproductsFromTo';
                    break;
                case 'Client':
                    url = 'onlinestoresync.php?do=updateonlineclientsFromTo';
                    break;
                case 'ClientDept':
                    url = 'onlinestoresync.php?do=syncClientsDeptOnlineFromTo';
                    break;
            }
            //start sending data
            sendData(url, type, from, afterFromId, to, tillEnd);
            $('#OS_' + type + '_Loading').hide();
            this_btn.removeClass('processing...');
        } else {
            alert('يرجى ادخال البيانات اولا');
            this_btn.removeClass('processing...');
        }
    }
});

function sendData(url, type, from, afterFromId, to, tillEnd) {
    var flag;
    $.ajax({
        type: "POST",
        url: url,
        data: {from: from, afterFromId: afterFromId, to: to, tillEnd: tillEnd},
        async: false,
        success: function (data) {
//            data = JSON.parse(data);
//            console.log(data);
//            data.forEach(function (element) {
//                element = element.split(",");
//                var store_id = element[0];
//            });
            afterFromId = 1;
            data = Number(data);
            flag = data;
            if (data == -1) {
                $('#OS_' + type + '_IdSpan').html('لا يوجد رابط للمتجر');
            } else if (data == -2) {
                console.log("error @ from = " + from);
            } else if (data > 0) {
                from = data;
                $('#OS_' + type + '_IdSpan').html(data);
            }
        },
        error: function (xhr, status, error) {
            console.log("error @ from = " + from + "error is: " + error);
        },
        complete: function (xhr, status) {
            if (Number(flag) > 0) {
                setTimeout(function () {//we need set time out even with zero time it allow html changes"last id updated" to be shown
                    sendData(url, type, from, afterFromId, to, tillEnd);
                }, 0);
            } else {
                alert('finished');
            }
        },
    });
}

$(document).on('click', '.saveIt', function () {
    var this_btn = $(this);
    if (!this_btn.hasClass('processing...')) {
        this_btn.addClass('processing...');
        var type = this_btn.data('type');
        var val = $('#' + type).val();

        if (val != "") {

            $('#OS_' + type + '_Loading').show();
            $('#OS_' + type + '_IdSpan').html("");
            $('#OS_' + type + '_Label').html("");
            $('#OS_' + type + '_Label').show();


            var url = '';
            switch (type) {
                case 'copyRightsStatment':
                case 'remoteBackupLink':
                case 'remoteBackupUser':
                case 'remoteBackupPass':
                case 'remoteBackupFolder':
                    url = 'gt4setting.php?do=saveajax';
                    break;
            }
            //start sending data


            var flag;
            $.ajax({
                type: "POST",
                url: url,
                data: {type: type, value: val},
                async: false,
                success: function (data) {
                    this_btn.removeClass('processing...');
                    $('#OS_' + type + '_Loading').hide();
                    data = Number(data);
                    if (data == 1) {
                        //$('#OS_' + type + '_IdSpan').html("");
                        $('#OS_' + type + '_Label').html("تم الحفظ");
                        if (type == 'copyRightsStatment') {
                            alert('تم الحفظ');
                            window.location.reload();
                        }

                    } else {
                        $('#OS_' + type + '_Label').html("حدث خطأ");

                    }
                },
                error: function (xhr, status, error) {
                    console.log("error : " + error);
                },
                complete: function (xhr, status) {
                    //alert('Done');
                },
            });


            $('#OS_' + type + '_Loading').hide();
            this_btn.removeClass('processing...');
        } else {
            alert('يرجى ادخال البيانات اولا');
            this_btn.removeClass('processing...');
        }
    }
});
$('.SaveWithManyParameters').live('click', function () {
    var this_btn = $(this);
    if (!this_btn.hasClass('processing...')) {
        this_btn.addClass('processing...');
        var type = this_btn.data('type');
        var dataToSend = {};

        if (type != "") {
            switch (type) {
                case 'calcTreeIds':
                    //prepare and validate data
                    var treeIdCalcTables = $('#treeIdCalcTables').val();
                    var treeIdCalcItems = $('[name="treeIdCalcItems"]:checked').val();
                    if (treeIdCalcTables == null) {
                        alert('اختر الجداول');
                        this_btn.removeClass('processing...');
                        return false;
                    }

                    //prepare parametes for json
                    dataToSend['treeIdCalcTables'] = treeIdCalcTables;
                    dataToSend['treeIdCalcItems'] = treeIdCalcItems;

                    break;
            }


            $('#OS_' + type + '_Loading').show();
            $('#OS_' + type + '_IdSpan').html("");
            $('#OS_' + type + '_Label').html("");
            $('#OS_' + type + '_Label').show();
            $.ajax({
                type: "POST",
                url: 'gt4setting.php?do=SaveWithManyParameters', //url,
                data: {type: type, dataToSend: dataToSend},
                async: false,
                success: function (data) {
                    //start sending data
                    $('#OS_' + type + '_Loading').hide();
                    this_btn.removeClass('processing...');

                    $('#OS_' + type + '_Loading').hide();
                    data = Number(data);
                    if (data == 1) {
                        //$('#OS_' + type + '_IdSpan').html("");
                        $('#OS_' + type + '_Label').html("تم الحفظ");
                        if (type == 'copyRightsStatment') {
                            alert('تم الحفظ');
                            window.location.reload();
                        }

                    } else {
                        $('#OS_' + type + '_Label').html("حدث خطأ");

                    }
                },
                error: function (xhr, status, error) {
                    console.log("error : " + error);
                },
                complete: function (xhr, status) {
                    //alert('Done');
                },
            });
        } else {
            alert('غير معرف');
            this_btn.removeClass('processing...');
        }
    }
});
$('#saveControlDevices').live('click', function () {
    $('#settingsForm').attr('action', 'gt4setting.php?do=saveControlDevices');
    $('#settingsForm').submit();
})
