

var TableEditable = function () {

    var forAll = function () {
        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.forcepositivefloat = 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 ||
                            //dot or point  .  on keyboard  for one time
                                    (key == 110 && $(this).val().indexOf(".") < 0) ||
                                    // Del and Ins
                                    key == 46 || key == 45)
                        return true;
                    return false;
                });
            });
        }


        $(document).ready(function (e)
        {
            $(".positiveNo").forcepositiveNum();
            $(".positivefloat").forcepositivefloat();
        });
    };
    var handleTable = function () {
        var hosturl = $("#hosturl").val();
        var getdata = function () {
            //happened in load the plugins
            //load all datalist
            var searchtxt = '';
            //name
            var listidn = 'namemedcine';
            $.post(hosturl + '/controllers/drugs.php?ac=getthisserach', {listid: listidn, searchtxt: searchtxt}, function (data) {
                //alert(data);
                //alert(listidn);
                $('#' + listidn).html(data);
                //alert($('#' + listidn).html());

                //cat
                var listidc = 'groupmedcine';
                $.post(hosturl + '/controllers/drugs.php?ac=getthisserach', {listid: listidc, searchtxt: searchtxt}, function (data) {
                    $('#' + listidc).html(data);
                    //dos
                    var listidu = 'usemedcine';
                    $.post(hosturl + '/controllers/drugs.php?ac=getthisserach', {listid: listidu, searchtxt: searchtxt}, function (data) {
                        $('#' + listidu).html(data);
                        //type
                        var listidf = 'frommedcine';
                        $.post(hosturl + '/controllers/drugs.php?ac=getthisserach', {listid: listidf, searchtxt: searchtxt}, function (data) {
                            $('#' + listidf).html(data);
                        });
                    });
                });
            });
        };
        function restoreRow(oTable, nRow) {
            var aData = oTable.fnGetData(nRow);
            var jqTds = $('>td', nRow);
            for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
                oTable.fnUpdate(aData[i], nRow, i, false);
            }
        }

        function editRow(oTable, nRow) {
            var aData = oTable.fnGetData(nRow);
            var jqTds = $('>td', nRow);
            jqTds[0].innerHTML = '<input type="text"   class="form-control input-small " value="' + aData[0] + '" disabled="disabled">';
            jqTds[1].innerHTML = '<input type="text"  list="groupmedcine" id="drugcatEdit"  class="form-control input-small testautocom getallwidth" value="' + aData[1] + '"><datalist id="groupmedcine"></datalist> ';
            jqTds[2].innerHTML = '<input type="text" list="namemedcine"  id="drugnameEdit"  class="form-control input-small testautocom getallwidth" value="' + aData[2] + '"><datalist id="namemedcine"></datalist> ';
            jqTds[3].innerHTML = '<input type="text" list="frommedcine" id="drugtypeEdit"  class="form-control input-small testautocom getallwidth" value="' + aData[3] + '"><datalist id="frommedcine"></datalist>';
            jqTds[4].innerHTML = '<input type="text" list="usemedcine" id="drugdosEdit"  class="form-control input-small testautocom getallwidth" value="' + aData[4] + '"><datalist id="usemedcine"></datalist>';
            jqTds[5].innerHTML = '<input type="text" class="form-control input-small " id="minimunBalanceEdit"  value="' + aData[5] + '">';
            jqTds[6].innerHTML = '<a class="edit" href="">Save</a>';
            jqTds[7].innerHTML = '<a class="cancel" href="">Cancel</a>';
            jqTds[8].innerHTML = '';
        }

        function addDrug(oTable) {
            var drugname = $('#drugname').val();
            var drugcat = $('#drugcat').val();
            var drugdos = $('#drugdos').val();
            var druguse = $('#drugtype').val();

            if (drugname == "" && drugcat == "" && drugdos == "" && druguse == "")
            {
                oTable.fnDeleteRow(nEditing);
                nEditing = null;
                nNew = false;
            } else
            {
                $.post(hosturl + '/controllers/drugs.php?ac=adddrug', $('#drugsForm').serialize(), function (data)
                {
                    if (Number(data) == 1)
                    {
                        oTable.fnDraw();
                        nEditing = null;
                        nNew = false;
                    } else
                    {
                        alert(data);
                    }
                });
            }
        }

        function updateDrug(oTable, drugId) {
            var drugname = $('#drugnameEdit').val();
            var drugcat = $('#drugcatEdit').val();
            var drugdos = $('#drugdosEdit').val();
            var druguse = $('#drugtypeEdit').val();
            var minimunBalance = $('#minimunBalanceEdit').val();

            if (drugname == "" && drugcat == "" && drugdos == "" && druguse == "")
            {
                oTable.fnDeleteRow(nEditing);
                nEditing = null;
                nNew = false;
            } else
            {
                $.post(hosturl + '/controllers/drugs.php?ac=updatedrug', {drugId: drugId, drugcat: drugcat, drugname: drugname, drugdos: drugdos, drugtype: druguse, minimunBalance: minimunBalance}, function (data)
                {
                    if (Number(data) == 1)
                    {
                        oTable.fnDraw();
                        nEditing = null;
                    } else
                    {
                        alert(data);
                    }
                });
            }
        }

        function newDrugRow(drugcat, drugname, drugdos, drugtype, minimunBalance) {
            $.post(hosturl + '/controllers/drugs.php?ac=getstores', {newItr: 1}, function (data) {
                var row = $('<tr></tr>');
                var col = $('<td colspan="8">'
                        + '<form id="drugsForm">'
                        + '<table class="table table-hover table-bordered" id="validateTable" style="margin-bottom: 0;">'
                        + '<tr>'
                        + '<td>Group <input type="hidden" id="validateItr" name="validateItr" value="1"></td>'
                        + '<td><input type="text" list="groupmedcine" name="drugcat"   id="drugcat" class="form-control  testautocom getallwidth" value="' + drugcat + '"> <datalist id="groupmedcine"></datalist></td>'
                        + '<td>Drug Name</td>'
                        + '<td><input type="text" list="namemedcine" name="drugname"   id="drugname" class="form-control   testautocom getallwidth" value="' + drugname + '"> <datalist id="namemedcine"></datalist></td>'
                        + '<td>Form</td>'
                        + '<td><input type="text" list="frommedcine" name="drugtype"  id="drugtype" class="form-control     testautocom getallwidth" value="' + drugtype + '"> <datalist id="frommedcine"></datalist></td>'
                        + '</tr>'
                        + '<tr>'
                        + '<td>Use</td>'
                        + '<td colspan="2"><input type="text" list="usemedcine" name="drugdos"  id="drugdos" class="form-control   testautocom getallwidth" value="' + drugdos + '"> <datalist id="usemedcine"></datalist></td>'
                        + '<td>Minimum balance / store</td>'
                        + '<td><input type="text"  id="minimunBalance" name="minimunBalance"  class="form-control   testautocom getallwidth positivefloat" value="' + minimunBalance + '"> </td>'
                        + '<td><a class="btn green btn-xs" float: left;" href="#" id="addNewValidate"><i class="fa fa-plus"></i></a></td>'
                        + '</tr>'
                        + '<tr>'
                        + '<td>Store</td>'
                        + '<td>' + data + '</td>'
                        + '<td>Validate To</td>'
                        + '<td><input type="text"  id="validateTo1" name="validateTo1" class="form-control datepicker"  value=""></td>'
                        + '<td>Initial balance</td>'
                        + '<td><input type="text"  id="quantity1" name="quantity1" class="form-control positivefloat"  value=""></td>'
                        + '</tr>'
                        + '</table>'
                        + '<table class="table table-hover table-bordered" style="margin-bottom: 0;">'
                        + '<tr>'
                        + '<td><a class="add_new btn green" href="">Save</a></td>'
                        + '<td><a class="cancel btn red" href="">Cancel</a></td>'
                        + '</tr>'
                        + '</table>'
                        + '</form>'
                        + '</td>');

                row.append(col).prependTo("#drug_edit");
                getdata();

                nEditing = true;
                nNew = true;

                $(".positivefloat").forcepositivefloat();
                $('.datepicker').datepicker({
                    todayBtn: "linked",
                    autoclose: true,
                    todayHighlight: true,
                    format: 'yyyy-mm-dd',
                    isRTL: true
                });

            });
        }

        var table = $('#drug_edit');
        var oTable = table.dataTable({
            // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
            // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js).
            // So when dropdowns used the scrollable div should be removed.
            //"dom": "<'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",

            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": hosturl + '/controllers/drugs.php?ac=show', //  server side processing
            "sPaginationType": "full_numbers",
            "aoColumnDefs": [
                {"sClass": "hide_me", "aTargets": [0]},
                {
                    'orderable': false,
                    "searchable": false,
                    "targets": [5]
                }, {
                    'orderable': false,
                    "searchable": false,
                    "targets": [6]
                }, {
                    'orderable': false,
                    "searchable": false,
                    "targets": [7]
                }, {
                    'orderable': false,
                    "searchable": false,
                    "targets": [8]
                }
            ],
            "lengthMenu": [
                [50, 100, 150, -1],
                [50, 100, 150, "All"] // change per page values here
            ],
            // set the initial value
            "pageLength": 50,
            "language": {
                "lengthMenu": " _MENU_ records"
            },
            "columnDefs": [{// set default column settings
                    'orderable': true,
                    'targets': [0]
                }, {
                    "searchable": true,
                    "targets": [0]
                }],
            "order": [
                [1, "asc"]       // order by drug cat
            ] // set first column as a default sort by asc
        });
        var tableWrapper = $("#sample_editable_1_wrapper");
        tableWrapper.find(".dataTables_length select").select2({
            showSearchInput: false //hide search box with special css class
        }); // initialize select2 dropdown

        var nEditing = null;
        var nNew = false;

        $('#sample_editable_1_new').click(function (e) {
            e.preventDefault();
            if (nNew && nEditing) {
                alert("Save previous record first .......");
            } else
            {
//                getdata();
                newDrugRow('', '', '', '', 0);
            }
        });

        table.on('click', '#addNewValidate', function (e)
        {
            var itr = $('#validateItr').val();
            var newItr = Number(itr) + 1;

            $.post(hosturl + '/controllers/drugs.php?ac=getstores', {newItr: newItr}, function (data) {
                $('#validateItr').val(newItr);

                var row = $('<tr></tr>');
                var col1 = $('<td>Store</td>'
                        + '<td>' + data + '</td>'
                        + '<td>Validate To</td>'
                        + '<td><input type="text"  id="validateTo' + newItr + '"  name="validateTo' + newItr + '" class="form-control datepicker"  value=""></td>'
                        + '<td>Initial balance</td>'
                        + '<td><input type="text"  id="quantity' + newItr + '"  name="quantity' + newItr + '" class="form-control positivefloat"  value=""></td>');

                row.append(col1).appendTo("#validateTable");
                $(".positivefloat").forcepositivefloat();
                $('.datepicker').datepicker({
                    todayBtn: "linked",
                    autoclose: true,
                    todayHighlight: true,
                    format: 'yyyy-mm-dd',
                    isRTL: true
                });
            });

        });

        table.on('click', '.delete', function (e)
        {
            e.preventDefault();
            if (confirm("Are you sure to delete this row ?") == false) {
                return;
            }

            var nRow = $(this).parents('tr')[0];
            var aData = oTable.fnGetData(nRow);
            var drugId = aData[0];

            if (drugId == "")
            {
                alert('Some thing wrong happened ......... ');
            } else
            {
                $.post(hosturl + '/controllers/drugs.php?ac=deletedrug', {drugId: drugId}, function (data)
                {
                    if (Number(data) == 1)
                    {
                        oTable.fnDeleteRow(nRow);
                    } else if (Number(data) == -1)
                    {
                        alert('can not be deleted , it contain drugs ......... ');
                    } else if (Number(data) == -2)
                    {
                        alert('can not be deleted , it is exist in store  ......... ');
                    } else {
                        alert(data);
                    }
                });
            }
        });

        table.on('click', '.cancel', function (e)
        {
            e.preventDefault();
            if (nNew) {
                oTable.fnDeleteRow(nEditing);
                nEditing = null;
                nNew = false;
            } else {
                restoreRow(oTable, nEditing);
                nEditing = null;
            }
        });

        table.on('click', '.edit', function (e)
        {
            e.preventDefault();
            getdata();
            /* Get the row as a parent of the link that was clicked on */
            var nRow = $(this).parents('tr')[0];
            if (nEditing !== null && nEditing != nRow) {
                /* Currently editing - but not this row - restore the old before continuing to edit mode */
                restoreRow(oTable, nEditing);
                nEditing = null;
                editRow(oTable, nRow);
                nEditing = nRow;
            } else if (nEditing == nRow && this.innerHTML == "Save")
            {
                /* Editing this row and want to save it */
                var aData = oTable.fnGetData(nRow);
                if (aData[0] === '') {
                    addDrug(oTable);
                } else
                {
                    var drugId = aData[0];
                    updateDrug(oTable, drugId);
                }

            } else {
                /* No edit in progress - let's start one */
                editRow(oTable, nRow);
                nEditing = nRow;
            }
        });

        table.on('click', '.duplicate', function (e)
        {
            e.preventDefault();
//            getdata();
            var nRow = $(this).parents('tr')[0];
            var aData = oTable.fnGetData(nRow);
            var drugname = aData[2];
            var drugcat = aData[1];
            var drugdos = aData[4];
            var drugtype = aData[3];
            var minimunBalance = aData[5];
            newDrugRow(drugcat, drugname, drugdos, drugtype, minimunBalance);
        });

        table.on('click', '.add_new', function (e)     // save new row
        {
            e.preventDefault();
            if (this.innerHTML == "Save")
            {
                addDrug(oTable);
            }
        });
    };

    var stores = function () {
        var hosturl = $("#hosturl").val();
        function restoreRow(oTable, nRow) {
            var aData = oTable.fnGetData(nRow);
            var jqTds = $('>td', nRow);
            for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
                oTable.fnUpdate(aData[i], nRow, i, false);
            }

            //oTable.fnDraw();
        }

        function editRow(oTable, nRow) {
            var aData = oTable.fnGetData(nRow);
            var jqTds = $('>td', nRow);
            jqTds[0].innerHTML = '<input type="text"   class="form-control input-small " value="' + aData[0] + '" disabled="disabled">';
            jqTds[1].innerHTML = '<input type="text" id="storeNameEdit"  class="form-control" value="' + aData[1] + '"><span id="storeNameEditError" style="color: red;"></span>';
            jqTds[2].innerHTML = '<a class="edit" href="">Save</a>';
            jqTds[3].innerHTML = '<a class="cancel" href="">Cancel</a>';
            // jqTds[4].innerHTML = '';
        }

        function addStore(oTable, storeName)
        {
            if (storeName == "")
            {
                $('#storeNameError').html('Store name can not be empty ');
            } else
            {
                $.post(hosturl + '/controllers/store.php?ac=addstore', {storeName: storeName}, function (data)
                {
                    if (Number(data) == -1)
                    {
                        $('#storeNameError').html('This name exist before');
                    } else
                    {
                        oTable.fnDraw();
                        nEditing = null;
                        nNew = false;
                    }

                });
            }

        }

        function updateStore(oTable, storeName, storeId) {
            if (storeName == "")
            {
                $('#storeNameEditError').html('Store name can not be empty ');
            } else
            {
                $.post(hosturl + '/controllers/store.php?ac=updatestore', {storeName: storeName, storeId: storeId}, function (data)
                {
                    if (Number(data) == -1)
                    {
                        $('#storeNameEditError').html('This name exist before');
                    } else
                    {
                        oTable.fnDraw();
                        nEditing = null;
                    }
                });
            }
        }


        var table = $('#stores_table');
        var oTable = table.dataTable({
            // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
            // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js).
            // So when dropdowns used the scrollable div should be removed.
            //"dom": "<'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",

            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": hosturl + '/controllers/store.php?ac=showstores', //  server side processing
            "sPaginationType": "full_numbers",
            "aoColumnDefs": [
                {"sClass": "hide_me", "aTargets": [0]},
                {
                    'orderable': false,
                    "searchable": false,
                    "targets": [2]
                }, {
                    'orderable': false,
                    "searchable": false,
                    "targets": [3]
                }
            ],
            "lengthMenu": [
                [50, 100, 150, -1],
                [50, 100, 150, "All"] // change per page values here
            ],
            // set the initial value
            "pageLength": 50,
            "language": {
                "lengthMenu": " _MENU_"
            },
            "columnDefs": [{// set default column settings
                    'orderable': true,
                    'targets': [1]
                }, {
                    "searchable": true,
                    "targets": [1]
                }],
            "order": [
                [1, "asc"]       // order by drug cat
            ] // set first column as a default sort by asc
        });
        var tableWrapper = $("#sample_editable_1_wrapper");
        tableWrapper.find(".dataTables_length select").select2({
            showSearchInput: false //hide search box with special css class
        }); // initialize select2 dropdown

        var nEditing = null;
        var nNew = false;
        $('#sample_editable_1_new').click(function (e) {
            e.preventDefault();
            if (nNew && nEditing) {
                alert("Save previous record first .......");
            } else
            {
                var row = $("<tr></tr>");
                var col1 = $('<td><input type="text"  id="storeName"  class="form-control" value=""><span id="storeNameError" style="color: red;"></span></td>');
                var col2 = $('<td><a class="saveStore" href="">Save</a></td>');
                var col3 = $('<td><a class="cancel" href="">Cancel</a></td>');
                row.append(col1, col2, col3).prependTo("#stores_table");

                nEditing = true;
                nNew = true;
            }

        });

        table.on('click', '.cancel', function (e)
        {
            e.preventDefault();
            if (nNew) {
                oTable.fnDeleteRow(nEditing);
                nEditing = null;
                nNew = false;
            } else {
                restoreRow(oTable, nEditing);
                nEditing = null;
            }
        });

        table.on('click', '.edit', function (e)
        {
            e.preventDefault();
            /* Get the row as a parent of the link that was clicked on */
            var nRow = $(this).parents('tr')[0];
            if (nEditing !== null && nEditing != nRow) {
                /* Currently editing - but not this row - restore the old before continuing to edit mode */
                restoreRow(oTable, nEditing);
                nEditing = null;
                editRow(oTable, nRow);
                nEditing = nRow;
            } else if (nEditing == nRow && this.innerHTML == "Save")
            {
                /* Editing this row and want to save it */
                var aData = oTable.fnGetData(nRow);
                if (aData[0] === '') {
                    //alert("Insert! Do not forget to do some ajax to sync with backend :)");
                    var storeName = $('#storeNameEdit').val();
                    addStore(oTable, storeName);
                } else
                {
                    var storeId = aData[0];
                    var storeName = $('#storeNameEdit').val();
                    updateStore(oTable, storeName, storeId);
                }

            } else {
                /* No edit in progress - let's start one */
                editRow(oTable, nRow);
                nEditing = nRow;
            }
        });


        table.on('click', '.saveStore', function (e)     // save new row
        {
            e.preventDefault();
            if (this.innerHTML == "Save")
            {
                var storeName = $('#storeName').val();
                addStore(oTable, storeName);
            }
        });


        table.on('click', '.delete', function (e)
        {
            e.preventDefault();
            if (confirm("Are you sure to delete this row ?") == false) {
                return;
            }

            var nRow = $(this).parents('tr')[0];
            var aData = oTable.fnGetData(nRow);
            var storeId = aData[0];

            if (storeId == "")
            {
                alert('Some thing wrong happened ......... ');
            } else
            {
                $.post(hosturl + '/controllers/store.php?ac=deletestore', {storeId: storeId}, function (data)
                {
                    if (Number(data) != 1)
                    {
                        alert('can not be deleted , it contain drugs ......... ');
                    } else
                    {
                        oTable.fnDeleteRow(nRow);
                    }
                });
            }
        });


    };

    var storesTransfer = function () {
        var hosturl = $("#hosturl").val();
        $('body').on('change', '#dname', function () {
            var drugId = $(this).val();
            $.post(hosturl + '/controllers/store.php?ac=search', {drugId: drugId}, function (res) {
                $('#searchResults').html(res);
            });
        });

        $('body').on('click', '.transferDrug', function () {
            var storeDrugsValidationId = $(this).attr('data-id');
            var itr = $(this).attr('data-itr');
            var movedBalance = $('#movedBalance' + itr).val();
            var storeTo = $('#stores' + itr).val();

            if (Number(movedBalance) > 0)
            {
                $.post(hosturl + '/controllers/store.php?ac=transferdrug', {storeDrugsValidationId: storeDrugsValidationId, movedBalance: movedBalance, storeTo: storeTo}, function (res) {
                    if (Number(res) == 1)
                    {
                        $('#dname').trigger('change');
                        alert('done ....');
                    } else
                    {
                        alert(res);
                        alert('error  .... please check if all data exist and press again ');
                    }
                });
            } else
            {
                alert('error  .... drug amount must be > 0 ');
            }

        });
    };


    var drugImport = function () {
        var hosturl = $("#hosturl").val();

        $('.datepicker').datepicker({
            todayBtn: "linked",
            autoclose: true,
            todayHighlight: true,
            format: 'yyyy-mm-dd',
            isRTL: true
        });

        var formatResult;

        formatResult = function (data) {
            return  data.text;
        };

        if ($('#drugImportEdit').val() == 1)
        {
        } else
        {
            if ($("#drug1").length > 0) {
                $("#drug1").select2({
                    placeholder: "Select drug name...",
                    width: '100%'
                });
            }

            if ($("#store1").length > 0) {
                $("#store1").select2({
                    placeholder: "Select store name...",
                    width: '100%'
                });
            }
        }



        $('body').on('click', '#newDrugImportRow', function () {
            var itr = $('#itr').val();
            var newItr = Number(itr) + 1;

            var drugs = $('#drugsload').html();
            var stores = $('#storesload').html();


            var newRow = '<tr>'
                    + '<td>'
                    + '<select id="drug' + newItr + '"    name="drug' + newItr + '" required>'
                    + drugs
                    + '</select>'
                    + '</td>'
                    + '<td>'
                    + '<select id="store' + newItr + '"    name="store' + newItr + '" required>'
                    + stores
                    + '</select>'
                    + '</td>'
                    + '<td>'
                    + '<input type="text" class="datepickertoday" id="validTo' + newItr + '" data-date-format="yyyy-mm-dd" placeholder="yyyy-mm-dd" name="validTo' + newItr + '"  required>'
                    + '</td>'
                    + '<td>'
                    + '<input type="text" class="positivefloat" placeholder="Amount" name="balance' + newItr + '" id="balance' + newItr + '" required>'
                    + '</td>'
                    + '<td>'
                    + '<button type="button" class="btn red minsprop hmt20"><i class="fa fa-close"></i></button>'
                    + '</td>'
                    + '</tr>';

            $('#itr').val(newItr);
            $('#plusitem').append(newRow);

            $(".positivefloat").forcepositivefloat();
            $('.datepickertoday').datepicker({
                todayBtn: "linked",
                autoclose: true,
                todayHighlight: true,
                format: 'yyyy-mm-dd',
                isRTL: true
            });

            if ($("#drug" + newItr).length > 0) {
                $("#drug" + newItr).select2({
                    placeholder: "Select drug name...",
                    width: '100%'
                });
            }

            if ($("#store" + newItr).length > 0) {
                $("#store" + newItr).select2({
                    placeholder: "Select store name...",
                    width: '100%'
                });
            }

        });
    };


    var receiptCaching = function () {
        var hosturl = $("#hosturl").val();
        $('.datepicker').datepicker({
            todayBtn: "linked",
            autoclose: true,
            todayHighlight: true,
            format: 'yyyy-mm-dd',
            isRTL: true
        });

        $('body').on('change', '#storeid', function () {
            var storeId = $(this).val();
            if (storeId == "")
            {
                $("#cachReceipt").hide();
                $("#cantCachReceipt").html('Choose Store First ...');
                $("#cantCachReceiptDiv").show();
            } else
            {
                var recepitTmpId = $("#id").val();
                $.post(hosturl + '/controllers/receipt.php?ac=checkamounts', {recepitTmpId: recepitTmpId, storeId: storeId}, function (data)
                {
                    var obj = JSON.parse(data);
                    console.log(obj);
                    if (Number(obj.cache) == 1)
                    {
                        $("#prescriptionDurgsTable").html(obj.res);
                        $("#cachReceipt").show();
                        $("#cantCachReceipt").html('');
                        $("#cantCachReceiptDiv").hide();
                    } else
                    {
                        $("#prescriptionDurgsTable").html(obj.res);
                        $("#cachReceipt").hide();
                        $("#cantCachReceipt").html('Cant cache this receipt ...');
                        $("#cantCachReceiptDiv").show();
                    }
                });
            }

        });


        $('body').on('click', '#cachReceiptBtn', function () {
            var storeId = $('#storeid').val();
            var valid = 1;
            if (storeId == "")
            {
                $("#cachReceipt").hide();
                $("#cantCachReceipt").html('Choose Store First ...');
                $("#cantCachReceiptDiv").show();
            } else
            {
                var doctorName = $('#doctorName').val();
                var doctorId = $('#doctorId').val();
                if (doctorName == "" && doctorId == "")
                {
                    valid = 0;
                } else
                {
                    var patientId = $('#patientId').val();
                    var patientName = $('#patientName').val();
                    if (patientName == "" && patientId == "")
                    {
                        valid = 0;
                    }
                }
            }

            if (valid == 1)
            {
                if ($('#type').val() == "internal")
                {
                    //alert(storeId);
                    $('#drugExportForm').append('<input type="text"  id="newStoreId" name="newStoreId" value="' + storeId + '">');
                }
                $.post(hosturl + '/controllers/receipt.php?ac=updatereceipt', $('#drugExportForm').serialize(), function (data)
                {
                    console.log(data);
                    if (Number(data) == 1)
                    {
                        window.location.href = hosturl + "/controllers/receipt.php?ac=show";
                    } else
                    {
                        $("#cachReceipt").hide();
                        $("#cantCachReceipt").html('Cant cache this receipt ... please try again later');
                        $("#cantCachReceiptDiv").show();
                    }
                });
            }

        });

        $('body').on('click', '#newDrugExportRow', function () {
            var storeId = $('#storeId').val();
            if (storeId == "" || storeId == -1)
            {
                alert('Choose Store First ...');
            } else
            {
                var itr = $('#itr').val();
                var newItr = Number(itr) + 1;

                var drugs = $('#drugsload').html();

                var newRow = '<tr>'
                        + '<td>'
                        + '<select class="form-control drugSelect " data-itr="' + newItr + '"  id="drug' + newItr + '"    name="drug' + newItr + '" required>'
                        + drugs
                        + '</select>'
                        + '</td>'
                        + '<td id="drugDetail' + newItr + '" colspan="3">'
                        + '</td>'
                        + '<td>'
                        + '<button type="button" class="btn red minsprop hmt20"><i class="fa fa-close"></i></button>'
                        + '</td>'
                        + '</tr>';

                $('#itr').val(newItr);
                $('#plusitem').append(newRow);

                if ($("#drug" + newItr).length > 0) {
                    $("#drug" + newItr).select2({
                        placeholder: "Select drug name...",
                        width: '100%'
                    });
                }

                $("#cachReceipt").show();
                $("#cantCachReceipt").html('');
                $("#cantCachReceiptDiv").hide();

            }
        });


        $('body').on('change', '#storeId', function () {
            var storeId = $(this).val();
            var itr = $('#itr').val();

            if (storeId == "" || storeId == -1)
            {
                $("#plusitem").hide();
                $("#cachReceipt").hide();
                $("#cantCachReceipt").html('Choose Store First ...');
                $("#cantCachReceiptDiv").show();
            } else
            {
                $("#plusitem").show();
                if (Number(itr) > 0)
                {
                    $("#cachReceipt").show();
                    $("#cantCachReceipt").html('');
                    $("#cantCachReceiptDiv").hide();
                }

            }


        });


        $('body').on('change', '.drugSelect', function () {
            var drugId = $(this).val();
            var storeId = $('#storeId').val();
            var itr = $(this).attr('data-itr');

            if (drugId == "" || drugId == -1)
            {
                $('#drugDetail' + itr).html('');
            } else
            {
                $.post(hosturl + '/controllers/receipt.php?ac=getdrugavailable', {drugId: drugId, storeId: storeId, itr: itr}, function (data)
                {
                    var obj = JSON.parse(data);
                    console.log(obj);
                    if (Number(obj.cache) == 1)
                    {
                        $('#drugDetail' + itr).html(obj.res);
                        $("#cachReceipt").show();
                        $("#cantCachReceipt").html('');
                        $("#cantCachReceiptDiv").hide();
                    } else
                    {
                        $('#drugDetail' + itr).html(obj.res);
                    }
                });
            }

        });


        $('body').on('change', '.searchReceipt', function () {
            var type = $(this).attr('data-type');
            var searchValues = Array();
            searchValues.push(type);
            searchValues.push($('#searchValue11').val());
            searchValues.push($('#searchValue21').val());
            searchValues.push($('#searchValue12').val());
            searchValues.push($('#searchValue22').val());
            var jsonString = JSON.stringify(searchValues);

            $.post(hosturl + '/controllers/receipt.php?ac=searchreceipt', {jsonString: jsonString}, function (data)
            {
                console.log(data);
                $('#' + type + 'ReceiptTable').html('');
                $('#' + type + 'ReceiptTable').html(data);
            });


        });
    };

    var reports = function () {
        var hosturl = $("#hosturl").val();
        $('.datepicker').datepicker({
            todayBtn: "linked",
            autoclose: true,
            todayHighlight: true,
            format: 'yyyy-mm-dd',
            isRTL: true
        });

        $('body').on('change', '.searchIn', function () {
            var searchValues = Array();
            searchValues.push($('#reportType').val());
            searchValues.push($('#searchValue1').val());
            searchValues.push($('#searchValue2').val());
            searchValues.push($('#searchValue3').val());
            searchValues.push($('#searchValue4').val());
            var jsonString = JSON.stringify(searchValues);

            $.post(hosturl + '/controllers/reports.php?ac=searchresult', {jsonString: jsonString}, function (data)
            {
                console.log(data);
                $("#resultTable").html(data);
            });


        });
    };
    return {
        //main function to initiate the module
        init: function () {
            forAll();
            if ($('#drugsController').val() == 1)
            {
                handleTable();
            } else if ($('#storesController').val() == 1)
            {
                stores();
            } else if ($('#storesTransfer').val() == 1)
            {
                storesTransfer();
            } else if ($('#drugImport').val() == 1)
            {
                drugImport();
            } else if ($('#receiptCaching').val() == 1)
            {
                receiptCaching();
            } else if ($('#reports').val() == 1)
            {
                reports();
            }
        }

    };
}();